Home > front end >  Decoding jwt token
Decoding jwt token

Time:11-21

Im trying to decode my jwt token that im receiving when im logging in, but it returns ''null'' in the console.log.

This is the code where im decoding:

import jwt from 'jsonwebtoken';

    function loginRequest(){
        const token = axios.post('https://afe2021fitness.azurewebsites.net/api/Users/login', 
        state).then(data => {localStorage.setItem('jwtToken', data.data.jwt);
        console.log(data.data.jwt)});

        console.log(jwt.decode(token));
    }

And i have also tried the decoder from the jwt-decode library without any luck:

var decoded = jwtdecode(token);

with this it says ''Uncaught (in promise) n {message: 'Invalid token specified'}''

CodePudding user response:

You should move the console.log(jwt.decode(token)) inside the then block or use an async function:

import jwt from 'jsonwebtoken';

async function loginRequest() {
  try {
    const { data } = await axios.post(
      'https://afe2021fitness.azurewebsites.net/api/Users/login',
      state
    );
    const token = data.jwt;
    localStorage.setItem('jwtToken', token);
    console.log(token);

    console.log(jwt.decode(token));
  } catch (err) {
    console.log(err);
  }
}

CodePudding user response:

The problem is that you tried to use token variable before you initialized it. You also needed to use await before Promise returned from axios.post. Now you have to use await before calling loginRequest. So the final code looks like this:

import jsonwebtoken from "jsonwebtoken";

async function loginRequest() {
  const response = await axios.post("https://afe2021fitness.azurewebsites.net/api/Users/login", state)
  const { jwt } = response.data
  localStorage.setItem("jwtToken", jwt);
  console.log(jwt);
  console.log(jsonwebtoken.decode(jwt));
}

  • Related