繁体   English   中英

如何在节点js中设置授权标头?

[英]How to set authorization header in node js?

您好,我正在开发节点应用程序,其中正在开发jsonwebtokens,passport-jwt。我创建了应用程序后端,并在邮递员上工作良好,但我停留在前端。 当我在邮递员的标头中发送令牌时,基于令牌的页面可以在邮递员处打开,但在正面显示未经授权。我如何在标头中发送令牌,以便此页面也可以在前端侧打开。 我的代码:

app.post("/login", function(req, res) {
  if(req.body.name && req.body.password){
    var name = req.body.name;
    var password = req.body.password;
  }

  var user = users[_.findIndex(users, {name: name})];
  if( ! user ){
    res.status(401).json({message:"no such user found"});
  }

  if(user.password === req.body.password) {
    // from now on we'll identify the user by the id and the id is the only personalized value that goes into our token
    var payload = {id: user.id};
    var token = jwt.sign(payload, jwtOptions.secretOrKey);
    //res.json({message: "ok", token: token});
   res.redirect('/secret')
  } else {
    res.status(401).json({message:"passwords did not match"});
  }
});

app.get("/secret", passport.authenticate('jwt', { session: false }), function(req, res){
    res.json("Success! You can not see this without a token");

  });

我在哪里做错了?

在您的/ login中,您可以将它们的令牌保存在sessionStorage中,以备将来使用...

像这样的东西

 if(user.password === req.body.password) {
  ....
        var payload = {id: user.id};
        var token = jwt.sign(payload, jwtOptions.secretOrKey);
        req.session.token = token ;
    }

}

使用此会话在客户端上更新sessionStorage

这是一篇文章 ,您需要在登录后保持登录状态...

您还需要在注销时销毁cookie

if you are getting token,you can send it as:

**

let headers = new Headers({'Content-Type':'application / json','Authorization':'Bearer'+ this.token});

**

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM