0

I make a class to create an axios api service. inside this class I fetch token(I got it from server and set it on cookie) from cookie.

const api = axios.create({
  headers: {
    common: {
      'Content-Type': 'application/json'
    },
    post: {

    }
  }
});


const cookies = parseCookies()
const token = cookies.token;
if (token && token !== 'undefined') {
  api.defaults.headers.common['Authorization'] = 'Bearer ' + token
}

because I import this api service from above component:

import api from "../../../services/httpService";

after login user, for another api calls cookie is null .

I think I have two solutions:

  1. I pass token to each api call like:

      const config = {
         headers: { Authorization: `Bearer ${cookies.token}` }
     };
      api.get('profile',config).then((res) => {
    

I don't want use this solution.

  1. re-create api import (but I don't know how I can).

1 Answer 1

1

When login success, you set token for cookies. And you should update a token for axios instance in this step.

// ... set token in cookies
api.defaults.headers.common['Authorization'] = 'Bearer ' + token

And you don't need this logic when create instance:

const cookies = parseCookies()
const token = cookies.token;
if (token && token !== 'undefined') {
  api.defaults.headers.common['Authorization'] = 'Bearer ' + token
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.