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 );
添加回答
舉報