admin管理员组文章数量:1277900
I am new to development, I have a task manager app in which I am using JWT tokens to verify, I can make it work on Postman, but I couldn't figure out how to store it through a browser and send it to server.
Here is what I am trying to do to make it work, but it says undefined outside the event listener, and I couldn't store the token to later send it to another url, I am sending the token to an API.
Here is my front end app.js code, for login page, on login the user is sent a JWT token :
let inMemoryToken;
const signInForm = document.querySelector( "#sign-in-form" );
signInForm.addEventListener( "submit", ( e ) => {
const email = document.querySelector( "#login-email" ).value;
const password = document.querySelector( "#login-pass" ).value;
e.preventDefault();
console.log( email, password );
fetch( "http://localhost:3000/users/login", {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify( {
"email": email,
"password": password,
} )
} ).then( res => res.json() )
.then( res => {
console.log( res );
let inMemoryToken = res.token;
console.log( inMemoryToken );
// { Authorization: `Bearer ${ inMemoryToken }`; }
return inMemoryToken;
} );
console.log( inMemoryToken );
return inMemoryToken;
} );
// inMemoryToken = res.body.token[ 0 ];
// let inMemoryToken2 = inMemoryToken;
console.log( inMemoryToken );
My back-end code for the log in is :
router.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( {
user,
token,
} );
} catch ( e ) {
res.status( 400 ).send( {
error: "Catch error",
e,
} );
}
} );
Also, after getting this token, I want to pass this to my tasks url, which is as :
const TaskForm = document.querySelector( "#add-tasks" );
TaskForm.addEventListener( "submit", ( e ) => {
const task = document.querySelector( '#task' ).value;
e.preventDefault();
console.log( task );
console.log( inMemoryToken );
fetch( "http://localhost:3000/tasks/", {
method: 'get',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Authorization': 'Bearer ${inMemoryToken}'
},
body: JSON.stringify( {
"Task": task
} )
} ).then( res => res.json() )
.then( res => console.log( res ) );
} );
I have been trying to solve this from 3 days, and couldn't get it to work, any help would be highly appreciated.
I am new to development, I have a task manager app in which I am using JWT tokens to verify, I can make it work on Postman, but I couldn't figure out how to store it through a browser and send it to server.
Here is what I am trying to do to make it work, but it says undefined outside the event listener, and I couldn't store the token to later send it to another url, I am sending the token to an API.
Here is my front end app.js code, for login page, on login the user is sent a JWT token :
let inMemoryToken;
const signInForm = document.querySelector( "#sign-in-form" );
signInForm.addEventListener( "submit", ( e ) => {
const email = document.querySelector( "#login-email" ).value;
const password = document.querySelector( "#login-pass" ).value;
e.preventDefault();
console.log( email, password );
fetch( "http://localhost:3000/users/login", {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify( {
"email": email,
"password": password,
} )
} ).then( res => res.json() )
.then( res => {
console.log( res );
let inMemoryToken = res.token;
console.log( inMemoryToken );
// { Authorization: `Bearer ${ inMemoryToken }`; }
return inMemoryToken;
} );
console.log( inMemoryToken );
return inMemoryToken;
} );
// inMemoryToken = res.body.token[ 0 ];
// let inMemoryToken2 = inMemoryToken;
console.log( inMemoryToken );
My back-end code for the log in is :
router.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( {
user,
token,
} );
} catch ( e ) {
res.status( 400 ).send( {
error: "Catch error",
e,
} );
}
} );
Also, after getting this token, I want to pass this to my tasks url, which is as :
const TaskForm = document.querySelector( "#add-tasks" );
TaskForm.addEventListener( "submit", ( e ) => {
const task = document.querySelector( '#task' ).value;
e.preventDefault();
console.log( task );
console.log( inMemoryToken );
fetch( "http://localhost:3000/tasks/", {
method: 'get',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'Authorization': 'Bearer ${inMemoryToken}'
},
body: JSON.stringify( {
"Task": task
} )
} ).then( res => res.json() )
.then( res => console.log( res ) );
} );
I have been trying to solve this from 3 days, and couldn't get it to work, any help would be highly appreciated.
Share Improve this question asked Jul 28, 2020 at 20:06 Abhishek SoniAbhishek Soni 2811 gold badge4 silver badges12 bronze badges1 Answer
Reset to default 7To store JWT on client you have two options: Cookies
or LocalStorage
strategies. I guess that you already know what a cookie is. LocalStorage is quite similar to a cookie, but enhanced and without sending information in headers (see Mozilla Developer definition), that's why LocalStorage is usually applied as persistant object.
Server side remains as you already have. No changes are needed.
On your client, in the handler of login response, you will store in LocalStorage your response from backend, like this:
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 plete object, so you will be able to access 'user' and 'token' later
On your task function, you should read LocalStorage for your object
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 );
本文标签:
版权声明:本文标题:javascript - How to store and handle JWT tokens on front-end using fetch, and how to store it? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741275793a2369721.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论