You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress中cy.intercept无法添加Authorization header问题排查

问题分析与解决方案

核心问题:拦截器内的Header设置代码被注释

你的代码里,cy.intercept中添加Authorization头的代码处于注释状态(//req.headers['Authorization'] = ...),这直接导致请求没有带上Token,自然返回401未授权。

额外注意事项(即使解开注释后可能遇到的问题)

  • cy.request不被cy.intercept拦截:Cypress的cy.request是绕过浏览器直接发起的HTTP请求,不会经过cy.intercept的拦截逻辑。如果目标是给cy.request统一加Header,应该用全局配置而非拦截器;拦截器仅对页面中发起的AJAX请求(比如fetch、XMLHttpRequest)生效。
  • 请求头大小写敏感:部分后端服务对Header键名的大小写严格区分,比如只接受小写的authorization而非大写的Authorization,可以尝试调整键名测试。
  • 拦截器时机与匹配规则:确保cy.intercept在目标请求发起前就已经设置完成,并且通配符*能正确匹配你要拦截的请求(如果是跨域请求,可能需要指定完整的URL前缀)。

修正后的代码示例

场景1:给页面AJAX请求统一加Token(用intercept)

cy.location('hash').then((hash) => {
    // 提取hash中的access_token
    const params = new URLSearchParams(hash.replace('#', ''));
    const accessToken = params.get('access_token');
    cy.log(`Adding Authorization header: Bearer ${accessToken}`);

    // 拦截所有页面发起的请求
    cy.intercept('*', (req) => {
      if (accessToken) {
        // 解开注释并确认Header键名格式
        req.headers['authorization'] = `Bearer ${accessToken}`;
      }
      // req.continue()可省略,默认会继续处理请求
    }).as('auth');

    // 页面发起的请求会被拦截器带上Header,比如模拟页面加载后的请求
    cy.visit('/some-page-that-makes-api-calls');
    cy.wait('@auth');
  });

场景2:给所有cy.request统一加Token(用全局配置)

cy.location('hash').then((hash) => {
    const params = new URLSearchParams(hash.replace('#', ''));
    const accessToken = params.get('access_token');
    cy.log(`Adding Authorization header: Bearer ${accessToken}`);

    // 全局配置所有cy.request的默认Header
    Cypress.Request.defaults({
      headers: {
        'Authorization': `Bearer ${accessToken}`
      }
    });

    // 后续的cy.request会自动带上Authorization头
    cy.request({
      url: '/v1/me',
      method: 'GET'
    }).then((response) => {
      expect(response.status).to.eq(200)
      expect(response.body).to.have.property('email')
    })
  });

内容的提问来源于stack exchange,提问作者Jerod Venema

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 02:37:17