I'm writing a nodejs api application using restify framework.
I'm enabling cors for cross domain access.
restify is configured with the following code:
var restify = require('restify'),
fs = require('fs');
var server = restify.createServer({
certificate: fs.readFileSync(__dirname + '/config/keys/myalcoholist/server.crt'),
key: fs.readFileSync(__dirname + '/config/keys/myalcoholist/server.key'),
name: 'MyAlcoholist',
});
function corsHandler(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token');
res.setHeader('Access-Control-Allow-Methods', '*');
res.setHeader('Access-Control-Expose-Headers', 'X-Api-Version, X-Request-Id, X-Response-Time');
res.setHeader('Access-Control-Max-Age', '1000');
return next();
}
function optionsRoute(req, res, next) {
res.send(200);
return next();
}
server.use(restify.bodyParser());
server.use(restify.CORS({
origins: ['http://127.0.0.1', 'https://myalcoholist.com', 'https://www.myalcoholist.com'], // defaults to ['*']
credentials: true, // defaults to false
headers: ['x-foo'], // sets expose-headers
methods: ['GET','PUT','DELETE','POST','OPTIONS']
}));
server.opts('/\.*/', corsHandler, optionsRoute);
server.listen(8888, function() {
console.log('%s listening at %s', server.name, server.url);
});
as you can see I implemented a corsHandler
function to handle OPTIONS request. the problem is that I'm having is that when I'm accessing this nodejs api from https://myalcoholist.com I get the following error in my google chrome browser:
XMLHttpRequest cannot load https://myalcoholist.com:8888/cocktail/get_latest_drinks. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
any ideas why I get this error ?
It seems that the answer it's pretty simple, I need to add Authorization
to the allowed headers. so my corsHandler function that works is the following:
function corsHandler(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token,Authorization');
res.setHeader('Access-Control-Allow-Methods', '*');
res.setHeader('Access-Control-Expose-Headers', 'X-Api-Version, X-Request-Id, X-Response-Time');
res.setHeader('Access-Control-Max-Age', '1000');
return next();
}