如何在nodejs中获取头文件请求

目前正在开发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

提前致谢!

使用JSONP时不能设置标题。 原因是因为当使用JSONP进行跨域请求时,jquery通过在DOM中注入一个特殊的<script>标签来加载远程资源来实现这一点。 正如你所知道的,当使用<script>标签时,你无法指定自定义标题。

JSONP的另一种方法是使用CORS 。 服务器将需要支持它,并明确允许需要设置的来源和标题。