在服务器端,一旦您创建了令牌并登录了用户,您就可以通过 res.send() 发送令牌,例如下面的示例,请注意您可能对函数 findByCredentials 和 GenreateAuthToken 有不同的方法,它们是自定义的:
app.post("/users/login", async (req, res) => {
try {
const user = await User.findByCredentials(
req.body.email,
req.body.password
);
const token = await user.generateAuthToken();
res.send({ token: user.tasks });
} catch (e) {
res.status(400).send();
}
});
在前端,您可以使用 html5 的 fetch() 在标头中发送令牌。例如,如果您想访问需要身份验证的“/users/me”,请按照以下步骤操作(但请确保先将令牌保存到本地存储,以便您可以通过 getItem 访问它:
localStorage.setItem('userInfo', JSON.stringify(userInfo));
document.getElementById("my-profile").addEventListener("click", getMe);
然后:
function getMe(e) {
e.preventDefault();
var token = JSON.parse(localStorage.getItem('token'));
console.log(`Authorization=Bearer ${token}`)
fetch('/users/me', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + token
}
})
.then(res => res.json())
.then(data => {
console.log(data)
// window.location.href = 'http://localhost:3000/dashboard';
})
.catch(err => { console.log(err) })
}