Reputation: 1110
I can't get the fetch() API to work. I get the strong feeling I'm doing something incorrectly.
I have a simple express server running on PORT 3005, which return data in json format, and a react.js client running on PORT 3000.
I'm using fetch()
to make a GET request to http://localhost:3005/api
but am getting these messages on the console
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3005/api. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
TypeError: NetworkError when attempting to fetch resource.
I added a header and read through similar questions but I still can't get it to work, and I'm still getting the same messages.
What am I doing wrong? (Here's the code)
let url = 'http://localhost:3005/api';
fetch(url, {
method: 'GET',
headers:{
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials':true,
'Access-Control-Allow-Methods':'POST, GET'
}
}).then(response => response.json)
.then(data => console.log(data))
I've run into this issue several times in the past, and usually just use axios. But this time, I want to get fetch()
to work...!
Upvotes: 2
Views: 10727
Reputation: 9555
Your server endpoint needs to support the Access-Control-Allow-Origin Header, not just the client.
The general flow is:
The client is doing a pre-flight request to check if the requested cors policy is supported by the server.
The server receives the pre-flight and answers with the right header when it deems the request allowed.
The client receives the answer and by the included headers knows if it is allowed the actual request.
(In your case) When the Header is not returned by the server, the browser will not allow the actual call and give the error you are experiencing.
So in order to solve it you need to modify the server code to return the correct Header for the preflight request.
Also see this stackoverflow answer.
See this link. Specifically look at the section about Preflight Requests.
Upvotes: 5