【发布时间】:2016-12-23 11:42:47
【问题描述】:
目前正在开发elasticsearch API应用程序,我需要从服务器端的AJAX调用中获取标头请求。下面给出了 Ajax 请求。
$.ajax({
url: 'http://localhost:3002/api/v1/getAutoSuggest/'+elasticsearchIndex+'/'+elasticsearchType,
dataType: 'JSONP',
type: 'GET',
beforeSend: function(xhr){xhr.setRequestHeader('access-control-request-headers', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9');},
success: function (data) {
}
});
在 nodejs 中,我尝试使用 req.headers['x-access-token'] 获取但无法获取。
var checkToken = app.use(function(req, res, next) {
var token = req.param.token || req.headers['x-access-token'];
if (token) {
jwt.verify(token, config.secret, function(err, decoded) {
if (err) {
return res.json({ success: false, message: 'Failed to authenticate token.' });
} else {
req.decoded = decoded;
next();
}
});
} else {
}
});
我还在nodejs服务器端添加了以下语句。
var allowedOrigins = ['http://127.0.0.1:8000', 'http://localhost:8000', 'http://127.0.0.1:9000', 'http://localhost:9000'];
var origin = req.headers.origin;
if(allowedOrigins.indexOf(origin) > -1){
res.setHeader('Access-Control-Allow-Origin', origin);
}
res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.header('Access-Control-Allow-Headers', 'access-control-request-headers');
res.header('Access-Control-Expose-Headers', '*');
res.header('Access-Control-Allow-Credentials', true);
但是得到小写的令牌eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9。
提前致谢!
【问题讨论】:
-
req.headers['x-access-token'] 为我工作
-
console.log(JSON.stringify(req.headers)) 返回什么?
标签: javascript jquery node.js authentication express