【问题标题】:Trying to set a cookie established on a web session as a header back to API尝试将在 Web 会话上建立的 cookie 设置为返回 API 的标头
【发布时间】:2023-03-18 08:03:02
【问题描述】:

我正在尝试通过 Web 前端登录并尝试拦截 cookie,然后在随后的 API 请求中使用它。我无法将 cookie 返回到 GET 请求中。代码贴在下面。

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();
    });

我尝试了几个示例,但完全无法弄清楚我缺少什么。

【问题讨论】:

    标签: testing automation automated-tests e2e-testing testcafe


    【解决方案1】:

    当您调用setCookie 方法时,您使用ClientFunction 修改浏览器中的cookie。 但是,当您调用 executeRequest 方法时,您会使用 nodejs 库在服务器端运行它。当您在客户端设置 cookie 时,这不会影响您从服务器端发送的请求。您需要将 cookie 信息直接添加到您的 options 对象中,如以下线程所述:How do I create a HTTP Client Request with a cookie?

    【讨论】:

      猜你喜欢
      • 2017-06-10
      • 2013-02-07
      • 1970-01-01
      • 2017-02-04
      • 2014-01-21
      • 2021-07-27
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      相关资源
      最近更新 更多