My Express server is running on port 8080 and I have the following middleware set up:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8081");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
When trying to make a request from port 8081 using fetch, I encounter an error:
fetch('http://localhost:8080/...')
.then((response) => response.json())
.then((json) => {
let jsonStr = JSON.stringify(json);
console.log(jsonStr)
})
.catch((error) => console.log(error))
The error message states:
Access to fetch at 'http://localhost:8080/...' from origin 'http://localhost:8081' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Oddly enough, when I manually enter the Express URL in the browser, I am able to see the JSON I am trying to fetch.
Despite reading several posts on resolving this issue, I am still unable to find a solution.
How can I adjust my fetch request to avoid this CORS error?