几天来,我一直在尝试为我的实习创建一个 React Web 应用程序,但我遇到了 CORS 错误。我正在使用最新版本的 reactJS,并将其放在 中create-react-app
,下面是获取代码:
componentDidMount() {
fetch('--------------------------------------------',{
method: "GET",
headers: {
"access-control-allow-origin" : "*",
"Content-type": "application/json; charset=UTF-8"
}})
.then(results => results.json())
.then(info => {
const results = info.data.map(x => {
return {
id: x.id,
slug: x.slug,
name: x.name,
address_1: x.address_1,
address_2: x.address_2,
city: x.city,
state: x.state,
postal_code: x.postal_code,
country_code: x.country_code,
phone_number: x.phone_number,
}
})
this.setState({warehouses: results, lastPage: info.last_page});
})
.then(console.log(this.state.warehouses))
}
很抱歉,由于公司规则,我无法发布 API 的 url,但是,已确认 API 后端中没有 CORS 设置。
但是,我在 mozilla 上运行时遇到以下错误
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ------------------. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
和
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ---------------------------------------------. (Reason: CORS request did not succeed).
如果在 chrome 上运行它会出现以下错误
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
和
Failed to load --------------------------------------------------------: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
和
Uncaught (in promise) TypeError: Failed to fetch
另一件事是我能够在浏览器中打开 url,没有任何问题或任何问题。
请帮助和感谢!
附加信息
我添加 CORS 设置的原因是它给出了 CORS 错误,因此删除它并不能真正解决问题。
接下来我尝试执行代理设置,但是,它现在给出
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
根据互联网,这是因为响应不是 JSON。但是,当我检查 API 时,它给出了这个
这意味着返回类型应该是 JSON 对吗?
附加信息
检查响应将产生这个
{"status":200,"total":1,"per_page":3,"current_page":1,"last_page":1,"next_page_url":null,"prev_page_url":null,"from":1," to":3,"data":[{"id":1,"slug":"america","name":"america","address_1":"USA Court","address_2":"USA", "city":"USA","state":"USA","postal_code":"94545","country_code":"US","phone_number":"10000001","created_by":null,"updated_by": null,"created_at":"2017-11-10 11:30:50+00","updated_at":"2018-06-28 07:27:55+00"}]}