当前位置:  开发笔记 > 编程语言 > 正文

允许带有restify的选项方法-请求头字段在飞行前响应中不允许Access-Control-Allow-Headers进行授权

如何解决《允许带有restify的选项方法-请求头字段在飞行前响应中不允许Access-Control-Allow-Headers进行授权》经验,为你挑选了1个好方法。

我正在使用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.

任何想法为什么我会收到此错误?



1> ufk..:

答案似乎很简单,我需要添加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();
}

推荐阅读
echo7111436
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有