简体   繁体   中英

How to set authorization header in node js?

Hello I am working on node application in which I am working on jsonwebtokens,passport-jwt.I created application backend side and working fine on postman but I stuck on front end side. when i send token in headers in postman then token based page open on postman fine but on front side display unauthorized.How can i send token in header so that this page also open on front end side. My code:

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");

  });

Where am i doing wrong??

in your /login you can save them tokens in a sessionStorage for future use...

something like this

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

}

use this session to update sessionStorage on client side

here is an article that is what you need for keeping logged in post login...

also you need to destroy the cookies on Logout

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

**

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

**

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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