javascript - 在反应中使用 fetch API 时输入意外结束
问题描述
我正在使用 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.
解决方案
首先更改mode: 'no-cors'
为mode: 'cors'
关于 CORS 问题
您需要更新您尝试从中请求信息的服务器上的 CORS 标头。这些 CORS 政策是出于安全目的而制定的
如果您有权访问它,请添加此标头:
'Access-Control-Allow-Origin: *'
或者
'Access-Control-Allow-Origin: http://example.com'
推荐阅读
- php - LDAP - 服务器 A -> 服务器 B -> LDAP
- ruby-on-rails - rspec 中的块之前在每个测试之前运行,它应该只运行一次
- javascript - 服务端渲染 JavaScript 的正确方式
- java - bootstrap.yml 未在 Spring Boot 2 中加载
- python - 无法找到 dict.iteritems(class) 的覆盖
- batch-file - 批处理文件中 sqlcmd 的用户指定脚本和输出文件夹
- android - Kotlin Android 错误消息,但应用运行良好
- verilog - 在verilog中带有reg类型的inout
- php - PHPUnit\Framework\TestCase 找不到 Symfony 4
- rust - 使用 LLDB 检查变量时的奇怪输出