CORS express not working predictably
MDN has a very short explanation on how a server should respond to a Preflight Request.
You handle CORS preflight requests by handling the HTTP OPTIONS method (just like you would handle GET and POST methods) before handling other request methods on the same route:
app.options('/login', ...);
app.get('/login'. ...);
app.post('/login'. ...);
In your case, it might be as simple as changing your app.use()
call to app.options()
, passing the route as the first argument, setting the appropriate headers, then ending the response:
app.options('/login', function (req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Methods', '*');
res.setHeader("Access-Control-Allow-Headers", "*");
res.end();
});
app.post('/login', function (req, res) {
...
});
After applying "cors" middleware. You should be passed "http://" before "localhost:". in url send to by Axios like this:
axios.get("http://localhost:8080/api/getData")
.then(function (response) {
this.items= response.data;
}).catch(function (error) {
console.log(error)
});
Configure the CORS stuff before your routes, not inside them.
Here, like this (from enable-cors.org):
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res, next) {
// Handle the get for this route
});
app.post('/', function(req, res, next) {
// Handle the post for this route
});
I always configure it like this in my Express+Angular apps and it works just fine.
Hope it helps.