I’m working on a web app that needs to get data from an external API service. When I test the API with curl commands, everything works fine and I get the expected response.
But when I try to make the same request using JavaScript fetch API, I keep running into CORS issues. Here’s the error I’m seeing:
Access to fetch 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.
I think the problem is related to cross-origin restrictions since I’m running my app on localhost. I tried adding CORS headers to my request but it doesn’t seem to work. Maybe I’m missing something in my implementation?
function authenticateUser() {
const requestHeaders = new Headers();
requestHeaders.append('Content-Type', 'application/json');
requestHeaders.append('Accept', 'application/json');
requestHeaders.append('Access-Control-Allow-Origin', 'http://localhost:3000');
requestHeaders.append('Access-Control-Allow-Credentials', 'true');
requestHeaders.append('GET', 'POST', 'OPTIONS');
requestHeaders.append('Authorization', 'Basic ' + btoa(userLogin + ":" + userPass));
fetch(apiEndpoint, {
//mode: 'no-cors',
credentials: 'include',
method: 'POST',
headers: requestHeaders
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log('Request failed: ' + err.message));
}
When I try using a CORS browser extension, I get a different error about wildcard origins not being allowed with credentials. Any ideas what I’m doing wrong here?