Home > Enterprise >  JWT returning false even after logged in
JWT returning false even after logged in

Time:08-04

I am trying to create a REACT JS ecommerce website. For auth part I am using JWT in node js. When logging in using api token is generated and user details are stored in db. But when calling an API for checking if jwt is signed in its returning false. The apis are working fine in postman. But when used in js its not working. Its like log in and user detail fetch apis are sending from different sessions. Why this problem is occuring.

async function getUserDetail() {
  var url = url_head   "me";
  var response = await fetch(url);
  const data = await response.json();
  console.log(data['success']);
  console.log(data)
  return data['success'];
}

async function loginUser() {
  var url = url_head   "login";

  var email = document.getElementById("loginemail");
  var password = document.getElementById("loginpass");
  if (email.value != "" && password.value != "") {
    var data = {
      email: email.value,
      password: password.value,
    };

    var response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });
    var body = await response.json();
    console.log(body);
    if(body['success'] == true){
        alert('Succesfully LoggedIn.');
        window.location.replace('/')
      }
      else{
        console.log(body['message']);
      }
  } else {
    alert("Please fill all the fields.");
  }
}

these are the fucntions to call API. APIS are hosted on heroku.

Please help me out

CodePudding user response:

  1. When you login you need to get your jwt token and store it in localStorage.
async function loginUser() {
  // ...
  var body = await response.json();
  localStorage.setItem('token', body.token)
}
  1. Then you take your token from localStorage and send it to your server like this.
async function getUserDetail() {
  const token = localStorage.getItem('token')
  let res = await fetch(url, {
    headers: {
      Authorization: `Bearer ${token}`
    }
  })

  let data = await res.json()
}
  • Related