'Cors Exception in Node.js
I am having cors error in a Node.js application as follows:
Access to XMLHttpRequest at 'http://localhost:8081/api/tutorials/1' from origin 'http://localhost:2240' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://localhost:8081' that is not equal to the supplied origin.
tutorial.component.js:91 Error: Network Error
at createError (createError.js:16:1)
at XMLHttpRequest.handleError (xhr.js:117:1)
xhr.js:210 PUT http://localhost:8081/api/tutorials/1 net::ERR_FAILED
The above are the messages from browser console. To avoid them, in the server-side with Express.js did the followings:
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
app.use(function(req, res, next) {
//Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
//Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
//Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
//Pass to next layer of middleware
next();
});
This actually occurs when I am trying to update an item in the database. So using axios, I am doing the following to do http request as follows:
import axios from "axios";
export default axios.create({
baseURL: "http://localhost:8081/api",
headers: {
"Content-type": "application/json"
}
});
But still couldn't sort this out. Any way to resolve it in the proper way?
Solution 1:[1]
The CORS origin should be the domain of the site that is connecting to the server, not the server's address.
Change the port to 8080 or whatever port your site is running on:
var corsOptions = {
origin: "http://localhost:8080"
};
This allows the browser to ensure that it only connects to the server from sites that are trusted.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pádraig Galvin |
