ReactJS API Data Fetching CORS error

Multi tool use
ReactJS API Data Fetching CORS error
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:
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.
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"}]}
package.json
"proxy": "http://yourAPI"
do not use response headers in a request (i.e.
access-control-allow-origin
is a response header) - this will inevitably trigger a CORS preflight, which the server may not understand - but, if the server doesn't allow CORS, there's nothing a client can do about it directly– Jaromanda X
Jul 2 at 1:33
access-control-allow-origin
it is confirmed that there are no CORS setting in the API backend - then CORS won't be allowed - you've answered your own question!!! read how CORS works here
– Jaromanda X
Jul 2 at 1:34
If not CORS enabled or api doesn't serve JSONP you have to use a proxy either on server you control or third party service
– charlietfl
Jul 2 at 1:37
it still throws a CORS error even if i removed the cors setting, to begin with it was only placed there after encountering a cors error. I will try the proxy thing first
– Last
Jul 2 at 1:51
1 Answer
1
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:
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-app
provides an easy way to do this: in your package.json
file, simply chuck "proxy": "http://your-company-api-domain"
. For more details, please see this link
create-react-app
package.json
"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.
fetch('/api/endpoints')
Hello, I added the proxy settings and the CORS error did disappear, but a new error appeared 'Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0'
– Last
Jul 2 at 3:59
@Last that means you bypass the CORS. But the response is not a valid JSON. Notice that the response has "<" as the first character so it's likely in XML format. Could you inspect your response and post it in your questtion?
– Dat Pham
Jul 2 at 4:02
Sorry to interrupt, but it is probably the proxy server responding with
404
.– Prajwal
Jul 2 at 4:04
404
what happens if the proxy server responds with 404?
– Last
Jul 2 at 5:26
posted the response
– Last
Jul 2 at 5:38
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Have you tried to set a proxy in your
package.json
? Somewhere above your dependencies:"proxy": "http://yourAPI"
– Vincent
Jul 2 at 1:33