Why fetch return a response with status = 0?(为什么 fetch 返回 status = 0 的响应?)
问题描述
我想使用 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.
这篇关于为什么 fetch 返回 status = 0 的响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 fetch 返回 status = 0 的响应?


基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01