javascript - 努力从 fetch api 获取数据以获取对 http://swapi.co 的 get 请求
问题描述
我正在努力从我的 localhost creat-react-app 项目向http://swapi.co.in发出成功的请求。我已将我的 fetch api 请求放在我的 main contianer 的 componentDidMount 中。
fetchData = () => {
return fetch('http://swapi.co/api/people', {method: 'GET'}).then((response) => {
console.log(response);
});
}
componentDidMount() {
this.fetchData();
}
给我一个错误
Failed to load http://swapi.co/api/people: Redirect from 'http://swapi.co/api/people' to 'https://swapi.co/api/people' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
1 Uncaught (in promise) TypeError: Failed to fetch
在我将我的 fecth Data 函数更新为
fetchData = () => {
return fetch('http://swapi.co/api/people', {
method: 'GET',
headers: {
'Access-Control-Allow-Origin': '*',
}
}).then((response) => {
console.log(response);
});
}
componentDidMount() {
this.fetchData();
}
它给出了一个错误
Failed to load http://swapi.co/api/people: Response for preflight is invalid (redirect)
:3000/#/:1 Uncaught (in promise) TypeError: Failed to fetch
我尝试了多种配置模式:cors, Access-Control-Allow-Origin: origin, others。他们都没有为我工作。
可能是什么问题?
解决方案
为什么您遇到 HTTP 请求问题
服务器发送以下标头:
HTTP/1.1 301 Moved Permanently
Date: Thu, 30 Aug 2018 19:20:06 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: max-age=3600
Expires: Thu, 30 Aug 2018 20:20:06 GMT
Location: https://swapi.co/api/people/
Server: cloudflare
CF-RAY: 45299ce127d321b6-EWR
这些都不是 CORS 标头,并且随着请求重定向,它需要 CORS。
怎么修
要解决此问题,您可以将 HTTP 更改为 HTTPS,从而避免重定向。
为什么自己添加标题不起作用
由于标头用于阻止网站发出请求,因此标头必须由服务器发送。如果网站可以发送此信息,那么 CORS 保护将不会添加任何内容。
推荐阅读
- python - 有没有办法解析 python-flask oauth2
- html - 如何将自定义字体插入 HTML?
- python - DataTable / 包含 Base 36 数据的列我需要转换为十进制
- google-cloud-platform - 回溯数据并在 Big Query 传输服务中自动添加新的 customerId
- javascript - 如何使 clearInterval 工作,为什么它不工作?
- javascript - 无法让我的菜单按钮在单击时显示菜单(使用内联 JS)
- typescript - 模型没有检测到张量,也没有检测到它们是可训练的
- python - 平均神经网络性能取决于 KFold 交叉验证中使用的折叠数
- c++ - ObjC / C++ 相同的代码具有不同的错误
- javascript - 从按钮传递两个不同的值并选择切换