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...!