techie_questie
techie_questie

Reputation: 1522

ReactJS- Pass the JWT token as Authorization in axios method for http request

I have an application where we are generating a JWT token and passing that token in Header in the next api call.As a response of that, I should get a key.I am able to see the response through postman.I am using ReactJS in Front End and trying to achieve the same by passing the JWT token in Header while doing the api call but facing some issues. My code-

getKey() {
    let postData = {
      vin: "5678",
      id: "abc12",
    };

axios({
      method: "post",
      url: "http://localhost:8080/generateKey",
      headers: {
        "Content-Type": "application/json"
      },
      data: postData
    })
      .then(function(response) {
        setKey(response.data.key);
      })
      .catch(function(error) {
        console.log(error);
        getKeyError();
      });
  }

  memberAuth() {
    var self = this;
    axios({
      method: "GET",
      url: "http://localhost:8080/authenticateMember",
      headers: {
        "Content-Type": "application/json",
        "Authorization": localStorage.setItem()
      },
      data: {
        "id":"xyzzy",
        "password":"abc"
      }
    })
      .then(function(response) {
        //to do

  }

I am trying to save the generated token (valid for 30mins) in a localStorage/SessionStorage but not sure if this is the right way. Can someone tell me where am I going wrong.

Upvotes: 0

Views: 1147

Answers (1)

Mohib Wasay
Mohib Wasay

Reputation: 321

Create instance of your axios,

const agent = axios.create({
  baseURL: config.api_url,
  transformRequest: [transformRequest],
  transformResponse: [transformResponse],
  headers: { 'Content-Type': 'application/vnd.api+json' },
});

And then call this function to set headers dynamically

agent.defaults.headers.common['Authorization'] = `JWT ${localStorage.getItem('token')}`;

Then call methods of your axios instance to make API calls

agent.get(`${endpoint}search`, { params }),
agent.post(`${endpoint}search`, JSON.stringify(body)),

Upvotes: 2

Related Questions