Javascript 如何在nodejs中获取头请求
目前正在开发ElasticSearchAPI应用程序,我需要从服务器端的AJAX调用获取头请求。下面给出了Ajax请求Javascript 如何在nodejs中获取头请求,javascript,jquery,node.js,authentication,express,Javascript,Jquery,Node.js,Authentication,Express,目前正在开发ElasticSearchAPI应用程序,我需要从服务器端的AJAX调用获取头请求。下面给出了Ajax请求 $.ajax({ url: 'http://localhost:3002/api/v1/getAutoSuggest/'+elasticsearchIndex+'/'+elasticsearchType, dataType: 'JSONP', type: 'GET', beforeSend: fun
$.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
提前谢谢 使用
JSONP
时不能设置标题。这是因为在跨域请求中使用JSONP
时,jquery通过向DOM中注入一个特殊的
标记来加载远程资源来实现这一点。正如您所知,当使用
标记时,您无法指定自定义标题
JSONP
的另一种方法是使用。服务器需要支持它,并显式允许需要设置的源和头。req.headers['x-access-token']适用于Meconsole.log(JSON.stringify(req.headers))返回什么?