首页 > 解决方案 > 如何存储和访问令牌以进行身份​​验证?

问题描述

app.post('/users/login', (req, res) => {
  var body = _.pick(req.body, ['email', 'password']);

  Users.findByCredentials(body.email, body.password).then((user) => {
         user.generateAuthTokens().then((token) => {
           res.header('x-auth', token).end();
         })
      }).catch((e) => res.send(e));
  });

在上面的代码中,user.generateAuthTokens()返回特定用户的令牌。我想将令牌存储在本地存储中,以便我可以在每个页面中访问它。我已经使用res.header()来设置令牌,但它不起作用,我如何才能在客户端读取存储的令牌?我曾经jsonwebtoken创建令牌。

标签: node.jsexpress

解决方案


您可以在 res.send 中发送令牌

Users.findByCredentials(body.email, body.password)
  .then((user) => {
    user.generateAuthTokens()
    .then((token) => {
      res.status(200).send({ auth: true, token: token });
    })
  })
  .catch((e) => res.send(e));

并使用前端浏览器的本地存储保存在客户端:

// To Save
localStorage.setItem('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c')


// To Access
localStorage.getItem('token')

或者您也可以在 HTTP 客户端中设置令牌

如果你使用 Axios

// Example HTTP request with axios
axios.post('/login', {
    username: 'test',
    password: 'test'
  })
  .then(function (response) {
    localStorage.setItem('token', response.data.token)
    
  })
  .catch(function (error) {
    console.log(error);
  });


// Set to default header Authorization with token
axios.defaults.headers.common['Authorization'] = localStorage.getItem('token')


推荐阅读