Reputation: 6734
My Node.js server code is running on an AWS instance. It looks like this:
var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var logger = require('morgan');
var cors = require('cors');
var SuperLogin = require('superlogin');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var config = {
dbServer: {
protocol: 'http://',
host: 'localhost:5984',
user: '',
password: '',
userDB: 'sl-users',
couchAuthDB: '_users'
},
mailer: {
fromEmail: '[email protected]',
options: {
service: 'Gmail',
auth: {
user: '[email protected]',
pass: 'userpass'
}
}
},
security: {
maxFailedLogins: 3,
lockoutTime: 600,
tokenLife: 86400,
loginOnRegistration: true,
},
userDBs: {
defaultDBs: {
private: ['supertest']
}
},
providers: {
local: true
}
}
// Initialize SuperLogin
var superlogin = new SuperLogin(config);
// Mount SuperLogin's routes to our app
app.use('/auth', superlogin.router);
app.listen(app.get('port'));
console.log("App listening on " + app.get('port'));
I am using an ionic 2 App that makes PUT calls to the Node.js server running on port 3000. When running the App in the browser on my laptop (using ionic serve
) the PUT call gives the CORS error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://ec2-xx-xxx-xx-4xx.eu-central-1.compute.amazonaws.com/auth/login.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
As far as I can tell the server code is setup to allow all origins but I am getting this error nonetheless.
Upvotes: 3
Views: 11802
Reputation: 1895
This is because the preflight is triggered, which means that an OPTIONS request will arrive at your server. This is well explained at this description by MDN as pointed out by @johannes merz in the comments to your question.
You can instruct your server to accept it by rep something like this:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
if ('OPTIONS' == req.method) {
res.sendStatus(200);
}
else {
next();
}});
Upvotes: 6