Home > Software engineering >  Item in local storage is undefined
Item in local storage is undefined

Time:08-18

Here the login method will return the token so I'm setting the token to local storage in login method and in auth.header function I'm justing getting the token and I'm using that token in getAllTweet. This getAllTweets methods accept token as parameter.
In login method console.log(responce.data) here it's printing the token but in getAllTweets it displaying error as undefined.

login(loginId, password) {
    return axios
      .post(API_URL   "login", {
        loginId,
        password
        
      })
      .then(response => {
        console.log(response.data);
        if (response.data) {
          localStorage.setItem("token", JSON.stringify(response.data));
        }
        console.log(response.data);
        return response.data;
});


export default function authHeader() {
  const token = JSON.parse(localStorage.getItem('token'));

  // if (user && user.token) {
    // console.log(user);
    // console.log(user.token);
    return token;
    // return { Authorization: 'Bearer '   user.accessToken }; // for Spring Boot back-end
    //return { 'x-access-token': user.accessToken };       // for Node.js Express back-end
  // } else {
  //   return {};
  // }
}
getAllTweet(authHeader) {
return axios.get(API_URL   'all',{
  headers: { Authorization: `Bearer ${authHeader} ` },
});

}

CodePudding user response:

do it like this. it will work as expected.

function authHeader() {
  const token = JSON.parse(localStorage.getItem('token'));
  return token;
}
getAllTweet() {
return axios.get(API_URL   'all',{
  headers: { Authorization: `Bearer ${authHeader()} ` },
});

CodePudding user response:

async function getAuthHeader() {
    const token = JSON.parse(localStorage.getItem('token')).then(token => {
      return { Authorization: `Bearer ${token} `}
  });
}

// using
const header = await getAuthHeader()

  • Related