【问题标题】:How to get header request in nodejs如何在nodejs中获取标头请求
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 2020-06-14
    • 2012-10-20
    • 2020-10-15
    • 2020-12-22
    • 1970-01-01
    相关资源
    最近更新 更多