1 回答
TA贡献1810条经验 获得超4个赞
要在客户端上存储 JWT,您有两种选择:Cookies或LocalStorage策略。我想您已经知道什么是 cookie。LocalStorage 与 cookie 非常相似,但有所增强且不在标头中发送信息(请参阅Mozilla 开发人员定义),这就是 LocalStorage 通常用作持久对象的原因。
服务器端保持不变。无需更改。
在您的客户端上,在登录响应的处理程序中,您将在 LocalStorage 中存储来自后端的响应,如下所示:
signInForm.addEventListener( "submit", ( e ) => {
. . .
fetch( "http://localhost:3000/users/login", {
. . .
} ).then( res => res.json() )
.then( res => {
console.log( res );
let inMemoryToken = res.token;
localStorage.setItem('user', JSON.stringify(res));
// 'user' is the generic key to sotre in LocalStorage. You could use any name you want
// Store complete object, so you will be able to access 'user' and 'token' later
在你的任务功能上,你应该为你的对象阅读 LocalStorage
const TaskForm = document.querySelector( "#add-tasks" );
TaskForm.addEventListener( "submit", ( e ) => {
const task = document.querySelector( '#task' ).value;
e.preventDefault();
console.log( task );
// ------ This is what you have to add --------
const localstorage_user = JSON.parse(localStorage.getItem('user'))
const inMemoryToken = localstorage_user.token
// -------------------------------------------
console.log( inMemoryToken );
添加回答
举报
