如何在expressjs中为json web token设置标头?

时间:2017-11-13 12:24:17

标签: javascript node.js

您好我正在使用express框架在nodeJs中进行模拟身份验证。我使用passport-jwt和jasonwebtoken进行身份验证。我创建了api并且在postman上工作得很好。但是我坚持在前端我无法在前端使用受保护的api。在邮递员中我使用标头发送令牌并且它运行良好。但是它不起作用在前端一侧。如何从前端端发送令牌和验证? 我的代码是:

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) {

    var payload = {id: user.id};
    var token = jwt.sign(payload, jwtOptions.secretOrKey);
    res.json({message: "ok", token: token});
  } 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");

  });

1 个答案:

答案 0 :(得分:0)

npm install cookie-parser

var cookieParser = require('cookie-parser') 
app.use(cookieParser())
app.use(function (req, res, next) {
var cookie = req.cookies.jwtToken;
if (!cookie) {
    res.cookie('jwtToken', theJwtTokenValue, 
             { maxAge: 900000, httpOnly: true });
} else {
    console.log('let's check that this is a valid cookie');
    // send cookie along to the validation functions...
}
next();
});