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.