如何将标头添加到 xhr-request

Rol*_*and 5 cypress

我有以下场景:

  • 一个通过 xhr-requests 基本上包含其他页面的起始页。

  • 一些 xhr 请求位于具有单点登录方案的防火墙后面,其中每个发送到服务器的 http 请求都从一组标头中剥离,然后根据用户授权进行填充。

  • 当请求到达服务器时,它期望某些请求具有 userId-header。
  • 测试服务器不在“防火墙”后面,所以我们在浏览器中有一个插件来模拟行为。

    We would like to run cypress-tests on this page. But we doesn't seem to find how to add this userId-header to the xhr-requests and havn't been able to find an example of this behaviour.

    Could you please provide an example that shows how to do this with a simple example?

An attemt to pseduo-code the scenario: cy.visit('myurl').interceptBeforeXhr('xhr-url').addHeader('xhr-url', {'userId' = 'username'})

Chr*_*ras 6

您可以使用headers属性来指定这样的标题:

describe('Test Cypress Custom Headers', function() {
  it('Visits Cypress Header Test Endpoint', function() {
    const Key = "test-key1";

    cy.visit({
      // An endpoint that expects a x-xhr-url header to grand access
      url: 'https://zikro.gr/dbg/so/59666650', 
      headers: {
        "x-xhr-url": Key
      }
    });

    cy.contains(`Access key: ${Key}`);
  })
});
Run Code Online (Sandbox Code Playgroud)

或者,request如果您想使用相同的标头发出多个请求,则可以使用:

describe('Test Cypress Custom Headers', function() {
  it('Visits Cypress Header Test Endpoint', function() {
    const Key = "test-key1";

    cy.request({
      url: 'https://zikro.gr/dbg/so/59666650',
      headers: {
        "x-xhr-url": Key
      }
    })
    .its('body').should('include', `Access key: ${Key}`);
  });
});
Run Code Online (Sandbox Code Playgroud)

两个测试都应该通过。

只是为了记录,这里是 PHP 端点头检查页面代码:

$headers = getallheaders();

if(isset($_SERVER['HTTP_X_XHR_URL'])) {
  echo "Access key: {$_SERVER['HTTP_X_XHR_URL']}";
} else {
  echo "Access denied";
}
Run Code Online (Sandbox Code Playgroud)

最后,如果您只想将标头值应用于所有 AJAX 请求,那么您应该使用和 使用设置标头,如下所示:server onAnyRequestproxyxhr

describe('Test Cypress Custom Headers', function() {
  it('Visits Cypress Header Test Endpoint', function() {
    const Key = "test-key1";

    cy.server({
      onAnyRequest: (route,  proxy) => {
        proxy.xhr.setRequestHeader('x-xhr-url', Key);
      }
    });

    cy.visit('https://zikro.gr/dbg/so/59666650/test-ajax.html');

    // Should pass the test of an AJAX call
    cy.contains(`Access key: ${Key}`);
  });
});
Run Code Online (Sandbox Code Playgroud)