我试图将Passport-Local登录请求发送到客户端,以供Satellizer分析,并且我希望来自服务器端的请求发送授权 token 。不幸的是,authorization中没有关键的request.headers:

{ host: 'localhost:3000',
  connection: 'keep-alive',
  'cache-control': 'max-age=0',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' }

登录函数将在此处重定向,这就是ensureAuthenticated()的调用位置。
app.get('/main', ensureAuthenticated, function(req, res, next){
    res.render('main.ejs', { token: createSendToken(req.user, config.secret), id: req.user._id, username: req.user.username, authorization: req.user.authorization });
});
ensureAuthenticated()然后分析登录请求并确保 token 匹配:
function ensureAuthenticated(req, res, next) {

  if (!req.headers.authorization) {
     return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });
  }
  var token = req.headers.authorization.split(' ')[1];

  var payload = null;
  try {
    payload = jwt.decode(token, config.token_secret);
  }
  catch (err) {
    return res.status(401).send({ message: err.message });
  }

  if (payload.exp <= moment().unix()) {
    return res.status(401).send({ message: 'Token has expired' });
  }
  req.user = payload.sub;
  next();
}

然后重定向并显示消息
{ message: 'Please make sure your request has an Authorization header' }

我如何为request.headers设置授权 key ?

最佳答案

要在请求中设置新的 header 字段,只需直接访问它即可,因为 header 对象看起来像普通的哈希表。

request.headers.authorization = value;

关于javascript - 在 Node request.headers中设置授权,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35315528/

10-16 21:23