0

I am trying to login via the webfront end and trying to intercept a cookie and then using that in the subsequent API request. I am having trouble getting the cookie back into the GET request. Code posted below.

import https from 'https';
import { bitbucketUser } from "../userRole.js"
import { ClientFunction } from 'testcafe';

fixture `Request/Response API`
 //   .page `https://myurl.company.com/login`
    .beforeEach(async t => {
        await t.useRole(bitbucketUser)
});

    test('test', async t => {
        const getCookie = ClientFunction(() => {
            return document.cookie;
        });
        var mycookie = await getCookie()

        const setCookie = ClientFunction(mycookie => {
            document.cookie = mycookie;
        });

        var validatecookie = await getCookie()
        console.log(validatecookie)
        const executeRequest = () => {    
            return new Promise(resolve => {

                const options = {
                    hostname: 'myurl.company.com',
                    path: '/v1/api/policy',
                    method: 'GET',
                    headers: {
                        'accept': 'application/json;charset=UTF-8',
                        'content-type': 'application/json' 
                    }
                };

                const req = https.request(options, res => {
                    console.log('statusCode:', res.statusCode);
                    console.log('headers:', res.headers);


                    let body = "";

                    res.on("data", data => {
                        body += data;
                      });

                    res.on("end", () => {
                        body = JSON.parse(body);
                        console.log(body);
                      });

                    resolve();
                });

                req.on('error', e => {
                    console.error(e);
                });

                req.end();
            });
        };      

        await setCookie(mycookie)
        await executeRequest();
    });

I have tried several examples but am quite not able to figure what is it that I am missing.

Alex Skorkin
  • 4,212
  • 3
  • 23
  • 46

1 Answers1

0

When you call the setCookie method, you modify cookies in your browser using the ClientFunction. However, when you call your executeRequest method, you run it on the server side using the nodejs library. When you set cookies on the client, this will not affect your request sent from the server side. You need to add cookie information directly to your options object as described in the following thread: How do I create a HTTP Client Request with a cookie?.

Alex Kamaev
  • 5,813
  • 1
  • 15
  • 28