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:
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.
However, I encounter the following errors when run on 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
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.
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.
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
api img
which means that return type should be a JSON right?
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"}]}
3条答案
按热度按时间n3h0vuf21#
需要在API中设置CORS设置,以允许从React应用程序域进行访问。**没有CORS设置,没有来自不同域的 AJAX **。就这么简单。您可以将CORS设置添加到公司API(不太可能发生这种情况),也可以按照以下所述进行变通:
CORS只是客户端浏览器的一种机制,用于保护用户免受恶意 AJAX 的攻击。因此,解决此问题的一种方法是将AJAX请求从React应用代理到其自己的Web服务器。正如Vincent所建议的,
create-react-app
提供了一种简单的方法来实现此目的:在您的package.json
文件中,只需chuck"proxy": "http://your-company-api-domain"
。有关详细信息,请参阅此链接然后在react应用中,您可以使用如下相对URL:
fetch('/api/endpoints')
。请注意,相对URL必须与您公司的API匹配。这将向您的服务器发送请求,然后服务器将请求转发给您公司的API,并将响应返回给您的应用。由于请求是以服务器到服务器而非浏览器到服务器的方式处理的,因此不会进行CORS检查。因此,您可以删除请求中所有不必要的CORS标头。myzjeezk2#
这是我用vite做的
Package.json文件添加:“代理服务器”:“请求正在通信的位置/",
应用程序组件或您进行调用的任何组件执行此操作
设终点=
/api/your_endpoint/
;gywdnpxw3#
您遇到的错误是跨源资源共享(CORS)错误,这是Web浏览器实现的安全功能。如果服务器不允许跨源请求,它将阻止从一个源到另一个源的请求。
有两种方法可以处理此错误:
1.修改服务器以允许跨源请求:您可以添加标题“访问-控制-允许-来源:* “添加到API的响应中,以允许来自任何来源的跨来源请求。
1.使用代理服务器:您可以将React应用配置为通过代理服务器发送API请求,而不是直接发送到API。这样,浏览器将不会阻止请求,因为请求看起来来自代理服务器而不是React应用。您可以在React应用的package.json文件中设置代理。以下是一个示例:
请注意,使用代理服务器只是一个临时的解决方案,最好将服务器配置为允许跨源请求。