为什么 fetch 返回 status = 0 的响应?

2022-01-19 00:00:00 frontend javascript ajax

我想使用 fetch API 从 URL 获取整个 HTML 文档.

I want to use fetch API to get a whole HTML document from URL.

let config = {
method: 'GET',
headers: {
    'Content-Type': 'application/json',
    'Accept': 'text/html',
    'Accept-Language': 'zh-CN',
    'Cache-Control': 'no-cache'
},
mode: 'no-cors'};

fetch('http://www.baidu.com', config).then((res)=> {
console.log(res);}).then((text)=> {});

当我在 chrome 中运行代码时,它会触发一个请求并在 chrome 网络选项卡中返回 html.但是 fetch res 返回:

When I run the code in chrome, It triggers a request and returns html in the chrome network tab. but fetch res return:

为什么状态为 0,我怎样才能获得像 chrome 网络中的那样正确的 res ?

Why status is 0 and how can I get the correct res like the one in the chrome network ?

推荐答案

关于no-cors config.mode 的一部分:

no-cors — 防止方法成为 HEAD、GET 或 POST 以外的任何方法.如果任何 ServiceWorkers 拦截了这些请求,它们可能不会添加或覆盖除这些之外的任何标头.此外,JavaScript 可能不会访问结果响应的任何属性.这可确保 ServiceWorker 不会影响 Web 的语义,并防止因跨域泄露数据而引起的安全和隐私问题.

no-cors — Prevents the method from being anything other than HEAD, GET or POST. If any ServiceWorkers intercept these requests, they may not add or override any headers except for these. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.

实际上,您通过发出此类请求(将 no-cors 指定为模式)得到的响应将不包含有关请求是成功还是失败的信息,从而使状态代码为 0.您的 fetch 调用中的 mode 将显示 CORS 实际上已失败.

Effectively, the response you get from making such a request (with no-cors specified as a mode) will contain no information about whether the request succeeded or failed, making the status code 0. Removing mode from your fetch call will show that the CORS had in fact failed.

要了解 0 在您的特定情况下的含义,请查阅其他 SO 答案.

To find out what 0 means in your particular case, consult other SO answers.

相关文章