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?
corsmiddleware.app.useblock), you don't need it.