CORS error using fetch API - React create app - javascript

I'm consuming an API using fetch but i'm getting CORS error.
I tried multiples headers, but I'm not understading what's the problem.
I'm not the owner of the API, so I couldn't change it, but checking the response it's returning access-control-allow-origin.
Following is my request method:
export const execPOST = (url, body) => {
return fetch(url, {
method: "POST",
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
body: JSON.stringify(body)
});
};
The response is:
Request URL: http://api
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: ip
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Access-Control-Allow-Origin: *
Isn't this response above enough to allow my request?
console error:
OPTIONS http://api net::ERR_ABORTED 405 (Method Not Allowed)
Access to fetch at 'http://api' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I got this working (meanwhile I develop) using "https://cors-anywhere.herokuapp.com/", but I don't think that I should use this for production enviroment.
I found a lot of material about this problem, but nothing that worked besides implements a backend to make the request or use something else as a proxy to make the request and so on...

Update code as given below (use 'mode' with the value 'no-cors' ):
For more details follow the link => https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
export const execPOST = (url: string, body: any) => {
return fetch(url, {
mode: 'no-cors',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
};

CORS headers are set by the API to protect users from malicious code making requests to sites on their behalf.
This means that you cannot enable or disable it from the client side as the Access-Control-Allow-Origin header is a server side only header.
If you don't have access to the API to change the headers then you won't be able to use the API from the client side.
In production you would have to create your own API that will handle the requests to the API you are trying to contact.

Related

Getting CORS error after allowing Origins

My frontend and backend services are in different origins, hence problem with CORS. But in my backend (python fastAPI) I have already added allow all origins:
api.add_middleware(
CORSMiddleware,
allow_origin_regex=".*",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
This is how my frontend is making the call
fetch('https://someurl.com/call', {
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
'Signature': btoa('0000')
},
body: new URLSearchParams({
})
}).then(res => {
return res.json()
})
Error that I am getting:
Access to fetch at 'https://someurl.com/call' from origin 'https://frontend.com' has been blocked by CORS policy: Request header field signature is not allowed by Access-Control-Allow-Headers in preflight response.
Is there something I am missing? Is my custom header 'Signature': btoa('0000') the problem?
I am trying to debug, this is what I am getting from the browser console

How to use Fetch API for GET request

I want to GET JSON from the endpoint https://api.brawlstars.com/v1/brawlers.
(https://api.brawlstars.com/v1/brawlers?Authorization="Bearer%20[My API Key]")
Here's my Code:
let url = 'https://api.brawlstars.com/v1/brawlers'
fetch(url, {
method: "GET",
headers: {
"Authorization": "Bearer **USER'S API KEY GOES HERE**"
}
}).then((response) => {
let json = response.json();
console.log(json);
}).catch((err) => {
console.error(err)
});
This is the output (error):
Access to fetch at 'https://api.brawlstars.com/v1/brawlers' from origin 'http://127.0.0.1:8887' has been
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If
an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS
disabled.
sketch.js:3 GET https://api.brawlstars.com/v1/brawlers net::ERR_FAILED
127.0.0.1/:1 Uncaught (in promise) TypeError: Failed to fetch
What am I missing?
In your header, you need to enable CORS like CBroe said :
headers.append('Access-Control-Allow-Origin', 'http://127.0.0.1:8887');
headers.append('Access-Control-Allow-Credentials', 'true');
Edit :
The server (that the POST request is sent to) needs to include the Access-Control-Allow-Headers header (etc) in its response. Putting them in your request from the client has no effect.
This is because it is up to the server to specify that it accepts cross-origin requests (and that it permits the Content-Type request header, and so on) – the client cannot decide for itself that a given server should allow CORS.

How to fetch data from different origin CORS? [duplicate]

This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed 3 years ago.
I'm trying to fetch data from a different origin to another server using Fetch API and I precise is from http to https
I can read the data from my browser but I don't know how to fetch them.
I already tried to set Access-Control-Allow-Origin to * but I still get this message :
I'm a little bit lost right know, Thank you for your support. 😁
const myHeaders = new Headers({
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
});
const fetchConfig = {
method: "GET",
headers: myHeaders,
mode: "cors",
cache: "no-cache"
};
function fetchData(url) {
fetch(url, fetchConfig)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => console.error(error));
}
fetchData("https://api.example.com/");
The Access-Control-Allow-Origin header needs to be set by the server you are retrieving the data from, in response to your request.
CORS Anywhere is a NodeJS proxy which adds CORS headers to the proxied request.
The URL to the proxy is literally taken from the path, validated and proxied. The protocol part of the proxied URI is optional, and defaults to "http". If port 443 is specified, the protocol defaults to "https".
This package does not put any restrictions on the http methods or headers, except for cookies. Requesting user credentials is disallowed. The app can be configured to require a header for proxying a request, for example, to avoid a direct visit from the browser.
You can simply add https://cors-anywhere.herokuapp.com/ at the beginning of your url.
Like this https://cors-anywhere.herokuapp.com/http://example.com/api/....
Check this link for more details: https://www.npmjs.com/package/cors-anywhere

Angular 7 : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested

I have to implement an angular application with CURD operations. API is already hosted IN AWS, Which is working fine with Postman.
But my angular application getting
Access to XMLHttpRequest at 'https://acp56df5alc.execute-api.us-east-1.amazonaws.com/ams/getmember' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My code is like below,
http_GET(actionUrl: string): Observable<any> {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
'key': 'x-api-key',
'value': 'NNctr6Tjrw9794gFXf3fi6zWBZ78j6Gv3UCb3y0x',
})
};
return this.http.get<any>(this.baseUrl + actionUrl, httpOptions).pipe(
(response => {
return response;
}));
}
I have tried hard to solve this.But need some help
I had the same cors issue and tried all the suggested ways of setting Access-Control-Allow-Origin * without success.
Later I found two issues:
The data format I sent via POST request was not properly formatted.
The server could not handle empty parameters received from the post request.
Original request:
return this.http.post(API_URL + 'customer/login',
{email: email, password: password},{ headers: headers}
)
Worked after i wrapped the post data using JSON.stringify()
return this.http.post(API_URL + 'customer/login',
JSON.stringify({email: email, password: password}),{ headers: headers}
)
All/Most of these headers need to be defined on the server-side (whatever hosts the API on AWS)... not client side.
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
'key': 'x-api-key',
'value': 'NNctr6Tjrw9794gFXf3fi6zWBZ78j6Gv3UCb3y0x',
...
The most likely reason that postman works is that it directly sends a GET request. what you are sending is a complex request which is called 'pre-flight' and which causes an 'OPTIONS' request to be sent before the actual GET. this is not allowed by the remote side.
That's a common CORS problem that (if you're using asp .net core on backend) can be solved enabling CORS following this thread

Why is Fetch API call not returning the response headers?

I'm building a SignUp form and have the following API call to POST the form:
const request = new Request('http://localhost:4300/auth/', {
method: 'POST',
headers: new Headers({
'Accept' : 'application/json',
'Content-Type' : 'application/json',
}),
body: JSON.stringify({ user: data })
});
fetch(request).then(response => {
console.log(response);
const auth = response.headers.get('Authorization');
console.log(auth)
});
The problem is response.headers.get('Authorization') is returning as null. Even though if I look at Chrome's Network XHR request I see the Response Headers being sent by the API server.
Why is React not providing me with response.headers via the request above?
Thanks
The value of the Access-Control-Expose-Headers response header for the response from http://localhost:4300/auth/ must include "Authorization" if you want your requesting frontend JavaScript code to be allowed to access the Authorization response header value.
If the response includes no value for the Access-Control-Expose-Headers header, the only response headers browsers will let you access from client-side JavaScript in your web app are Cache-Control,
Content-Language,
Content-Type,
Expires,
Last-Modified
and
Pragma.
See https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name for the spec.

Categories