【发布时间】:2019-02-05 18:37:35
【问题描述】:
我正在努力从我的 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 到 https 进行重定向......
-
尝试将您的获取请求从 HTTP 更改为 HTTPS
标签: javascript cors fetch