【问题标题】:Response headers not available for fetch request with 'redirect: manual'响应标头不适用于“重定向:手动”的获取请求
【发布时间】:2019-03-10 23:54:24
【问题描述】:

我在做

        console.log("navigating");
        var rsp = await fetch(params.url, {
            credentials: "include", redirect: "manual", mode: "cors"
        });
        console.log(rsp);
        rsp.headers.forEach(console.log);

        console.log(rsp.headers.get('Location'));
        console.log(rsp.headers.get('location'));

以及来自 chrome 开发工具的响应标头:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4400
Access-Control-Expose-Headers: Location
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 0
Date: Fri, 05 Oct 2018 12:48:21 GMT
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Location: http://localhost/test

给予

Response 
body: (...)
bodyUsed: falseheaders: 
Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaqueredirect"
url: "..."

index.ts:161 null
index.ts:162 null

是否无法在重定向响应中获取响应标头?

【问题讨论】:

    标签: fetch-api


    【解决方案1】:

    是否无法在重定向响应中获取响应标头?

    不,这是不可能的。 Fetch 规范中的要求阻止了它。

    manual 重定向模式预期的问题显示:在响应 redirect: "manual" 请求时,暴露给前端 JS 的 headers 对象预计为空。

    当请求设置manual重定向模式时,响应类型为opaqueredirect。有关其效果的信息在https://developer.mozilla.org/en-US/docs/Web/API/Response/type

    opaqueredirect:获取请求是使用redirect: "manual" 发出的。 Response 的状态为 0,headers 为空,body 为 null,trailer 为空。


    该 MDN 文章中的详细信息直接基于 Fetch 规范的以下部分:

    https://fetch.spec.whatwg.org/#concept-request-redirect-mode

    请求具有关联的重定向模式,即"follow""error""manual"

    “manual”:当请求遇到重定向时,检索不透明重定向过滤响应,以便可以手动执行重定向。

    https://fetch.spec.whatwg.org/#concept-filtered-response-opaque-redirect

    opaque-redirect过滤响应是过滤响应,类型为"opaqueredirect",状态为0,状态消息为空字节序列,header列表为空,正文为空

    不透明过滤响应和不透明重定向过滤响应几乎无法与网络错误区分开来

    【讨论】:

    • "manual:当请求遇到重定向时检索不透明重定向过滤响应,以便可以手动执行重定向"response.url 不是重定向 URL,它的原始 URL。如果我不知道重定向 URL 是什么,如何手动处理重定向?
    • @Madbreaks 是的,您实际上并不想使用“手动”;请参阅stackoverflow.com/a/42717388/441757 的答案。
    猜你喜欢
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 2015-10-18
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    相关资源
    最近更新 更多