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

使用Playwright无法获取Location响应头,如何解决?

解决Playwright request无法获取Location响应头的问题

核心原因

Playwright的request API默认会自动跟随重定向,你当前拿到的response是最终跳转后的响应,而非最初返回Location头的3xx重定向响应,因此看不到Location头。

解决步骤

  1. 禁用自动重定向
    在post请求配置中添加followRedirect: false参数,这样就能获取到原始的3xx响应,从中提取Location头:

    const pw = await request.newContext({
        ignoreHTTPSErrors: true,
        extraHTTPHeaders: { 'my-device-id': 'value' } 
    });
    
    const response = await pw.post(fsUrl, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        form: {
            UserName: usr.login,
            Password: usr.password,
            AuthMethod: 'FormsAuthentication',
        },
        followRedirect: false // 新增:禁用自动重定向
    });
    
    console.log(response.status()); // 先确认是否为3xx状态码
    console.log(response.headersArray()); // 此时就能看到Location头
    
  2. 验证响应状态
    先打印response.status()确认是否为3xx(比如301、302),如果是200则说明请求没有触发重定向,自然不存在Location头。

关于Access-Control-Expose-Headers的说明

你尝试添加的这个请求头是用于浏览器前端跨域场景的,控制哪些响应头能被前端JS访问。但Playwright的request context是直接发送HTTP请求,不受CORS规则限制,所以加这个头完全没用,无需添加。

内容的提问来源于stack exchange,提问作者Vadim Tokaev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:47:34