【发布时间】:2019-10-19 00:49:17
【问题描述】:
我正在使用 fetch 来简单地从虚拟 api 端点获取数据,但是当我在 fetch 函数中添加配置时,我得到了一个意外的输入结束错误。
这很好用,控制台记录了一个包含 200 个项目的数组
componentDidMount() {
let url = 'https://jsonplaceholder.typicode.com/todos';
let config = {
method: "GET",
mode: "no-cors",
headers: {
"access-control-allow-origin" : "*",
"Content-type": "application/json; charset=UTF-8",
"access-control-allow-headers": "content-type"
}
};
fetch(url)
.then(res => res.json())
.then(data => this.setState({ data, }))
}
但是当我将配置作为参数添加时,它会显示并出错。
componentDidMount() {
let url = 'https://jsonplaceholder.typicode.com/todos';
let config = {
method: "GET",
mode: "no-cors",
headers: {
"access-control-allow-origin" : "*",
"Content-type": "application/json; charset=UTF-8",
"access-control-allow-headers": "content-type"
}
};
fetch(url, config) // This is where the error occurs
.then(res => res.json())
.then(data => this.setState({ data, }))
}
错误:
Dashboard.jsx:35 Uncaught (in promise) SyntaxError: Unexpected end of input
at Dashboard.jsx:35
和
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://jsonplaceholder.typicode.com/todos with MIME type application/json.
【问题讨论】:
-
为什么要从客户端获取 API 发送
access-control-allow-origin(CORS) 标头。这些应该从服务器发送以避免跨域问题。删除access-control-allow-headers和access-control-allow-origin标头。这是工作code sandbox link
标签: javascript reactjs cors fetch