我正在使用restify框架编写一个nodejs api应用程序。
我正在启用cors进行跨域访问。
restify配置有以下代码:
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); });
如您所见,我实现了一个corsHandler
处理OPTIONS请求的功能。问题是我遇到的是,当我从https://myalcoholist.com访问此nodejs api时,我在Google chrome浏览器中收到以下错误:
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.
任何想法为什么我会收到此错误?
答案似乎很简单,我需要添加Authorization
到允许的标题中。所以我的corsHandler函数起作用如下:
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(); }