Javascript ReactJS API 数据获取 CORS 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51128176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ReactJS API Data Fetching CORS error
提问by Last
I've been trying to create a react web app for a few days now for my internship and I've encountered a CORS error. I am using the latest version of reactJS, and placing this in the create-react-app, and below is the code for fetching:
几天来,我一直在尝试为我的实习创建一个 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))
}
I'm sorry that I can't post the url for the API due to company rules, however, it is confirmed that there are no CORS setting in the API backend.
很抱歉,由于公司规则,我无法发布 API 的 url,但是,已确认 API 后端中没有 CORS 设置。
However, I encounter the following errors when run on mozilla
但是,我在 mozilla 上运行时遇到以下错误
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ------------------. (Reason: CORS header ‘Access-Control-Allow-Origin' missing).
and
和
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ---------------------------------------------. (Reason: CORS request did not succeed).
If run on chrome it gives the following error
如果在 chrome 上运行它会出现以下错误
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
and
和
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.
and
和
Uncaught (in promise) TypeError: Failed to fetch
Another thing is that I am able to open the url in my browsers with no problems or whatsoever.
另一件事是我能够在浏览器中打开 url,没有任何问题或任何问题。
Please help and thanks!
请帮助和感谢!
Additional Information
附加信息
The reason I added the CORS setting is because it gives a CORS error, so removing it does not really solve the issue.
我添加 CORS 设置的原因是因为它给出了 CORS 错误,因此删除它并不能真正解决问题。
Next I tried to perform proxy setting, however, it now gives
接下来我尝试执行代理设置,但是,它现在给出
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
According to the internet this is caused becasue the response is not a JSON. However when I checked the API it gives this
根据互联网,这是因为响应不是 JSON。但是,当我检查 API 时,它给出了这个
which means that return type should be a JSON right?
这意味着返回类型应该是 JSON 对吗?
Additional Info
附加信息
checking the respond will yield this
检查响应将产生这个
{"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"}]}
{"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"}]}
回答by Dat Pham
The CORS settings need to be setup in the API to allow access from your React app domain. No CORS settings, no AJAX from different domains. It's simple as that. You can either add CORS settings to your company API (this is unlikely to happen) or you can work around like described below:
需要在 API 中设置 CORS 设置以允许从您的 React 应用程序域进行访问。没有 CORS 设置,没有来自不同域的 AJAX。就这么简单。您可以将 CORS 设置添加到您的公司 API(这不太可能发生),或者您可以像下面描述的那样解决:
The CORS is solely a mechanism of client browser to protect users from malicious AJAX. So one way to work around this is proxying your AJAX request from your React app to its own web server. As Vincent suggests, the create-react-appprovides an easy way to do this: in your package.jsonfile, simply chuck "proxy": "http://your-company-api-domain". For more details, please see this link
CORS 只是一种客户端浏览器保护用户免受恶意 AJAX 攻击的机制。因此,解决此问题的一种方法是将来自 React 应用程序的 AJAX 请求代理到其自己的 Web 服务器。正如文森特所建议的,create-react-app提供了一种简单的方法来做到这一点:在您的package.json文件中,只需 .chuck "proxy": "http://your-company-api-domain"。有关更多详细信息,请参阅此链接
Then in your react app you can using relative URL like this: fetch('/api/endpoints'). Notice that the relative URL has to match with your company API. This will send a request to your server, then the server will forward the request to your company API and return the response back to your app. Since the request is handled in the server-to-server way not browser-to-server so the CORS check won't happen. Therefore, you can get rid of all unnecessary CORS headers in your request.
然后在你的应用程序的反应,你可以使用相对URL是这样的:fetch('/api/endpoints')。请注意,相对 URL 必须与您公司的 API 匹配。这将向您的服务器发送请求,然后服务器将请求转发到您公司的 API 并将响应返回给您的应用程序。由于请求是以服务器到服务器的方式处理的,而不是浏览器到服务器的,因此不会发生 CORS 检查。因此,您可以删除请求中所有不必要的 CORS 标头。

