首页 > 解决方案 > 无法通过钩子将标头值添加到 HTTP 请求

问题描述

使用 Testcafe,我正在尝试向我的所有请求添加一个 HTTP 标头键/值对,但是当我在实时模式下检查浏览器中的网络请求时,它没有出现在请求标头中。

我想知道这是否可能是 TypeScript 的问题?我不得不修改文档中的示例代码以允许方法参数为类型any以使其编译,这令人惊讶,因为我在其他地方没有看到该要求,TC 只是“处理”它。

那么两个问题:

这是代码:

import { RequestHook } from 'testcafe';

export class WebSwitchHook extends RequestHook
{
    constructor(requestFilterRules: any, responseEventConfigureOpts: any)
    {
      super(requestFilterRules, responseEventConfigureOpts);
      // ...
    }

    async onRequest (e: any)
    {
      e.requestOptions.headers['wafAccessToken'] = "REDACTED";
      console.log(e.requestOptions);
    }

    async onResponse (e: any) {
      console.log(e.body);
    }
}

const webSwitchHook = new WebSwitchHook("http://www.google.com", {
  includeHeaders: true,
  includeBody: true
});

fixture.only('Test')
.page("http://www.google.com")
.requestHooks(webSwitchHook);

test('Test', async t => {
  
});

标签: testingautomationautomated-testse2e-testingtestcafe

解决方案


您共享的代码可以正常工作。您可以看到您在服务器上添加的标头。您还可以将RequestLogger附加到夹具并在那里查看更新的标头。

至于您的第二个问题,您可以使用此示例中的代码RequestHook对所有请求使用:

class JwtBearerAuthorization extends RequestHook {
    constructor () {
        super();
    }

    //...
}

或者,将正则表达式传递给 RequestHook 构造函数以仅将其用于匹配 URL。


推荐阅读