node.js - 如何存储和访问令牌以进行身份验证?
问题描述
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
创建令牌。
解决方案
您可以在 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')
推荐阅读
- angular - jsPlumb 函数失败:TypeError:无法读取未定义的属性(正在读取“resetBounds”)
- python - 使用 Deeplabv3+ keras 进行二元语义分割(专为多类语义分割而设计)
- python - 给定一个数组,什么是创建数组数组的有效方法,其中每个子数组的索引与给定数组中的值相等
- python - 检查熊猫数据框行的值
- laravel - laravel 测试可邮寄附件已发送
- apache-spark - spark jdbc api 在访问具有 Map 数据类型列的配置单元表时出错
- html - CSS Border-radius 创建弯曲形状
- iis - 带有 Windows 导出器的 IIS 指标
- javascript - 如何在 HTML 代码中从 CDN 和 JS 脚本链接 jQuery
- clang - 使用 llvm-mc 时有没有办法打印出字符串和调试消息?