Home > Software design >  Add additional headers in Axios create function
Add additional headers in Axios create function

Time:09-27

I have this already made function to send requests from Axios,

export const http = axios.create({
  baseURL: 'https://someurl/api',
  headers: {
    'Content-type': 'application/json',
    Accept: 'application/json',
  },
});

So I can call this method anywhere in my application,

   import {http} from 'src/helpers/HttpHelper';

   http
      .post(
        '/users',
        {name: 'mishen'},
      )
      .then(res => console.log(res))
      .catch(error => console.log());

Since there are protected routes too which require a bearer token I tried to do something like this inside my component,

import {useContext} from 'react';
import {http} from 'src/helpers/HttpHelper';

const MyComponent = () => {
  const {userToken} = useContext(AuthContext);
  const signUpUser = () => {
    http
  .post(
    '/app_user_role_selection',
    {name: 'mishen'},
    {headers: {Authorization: `Bearer ${userToken}`}}
  )
  .then(res => console.log(res))
  .catch(error => console.log());
 }
 ...
}

However, this is not working.

CodePudding user response:

You can use axios interceptors.

export const http = axios.create({
  baseURL: "url",
  headers: {
    "Content-type": "application/json",
    Accept: "application/json"
  }
});

http.interceptors.request.use(async (config) => {
  const value = await AsyncStorage.getItem("your key");
  if (value !== null) {
    config.headers["Authorization"] = `Bearer ${value}`;
  }

  return config;
});


const MyComponent = () => {
  const signUpUser = () => {
    http
      .post(
        "/app_user_role_selection",
        { name: "mishen" }
      )
      .then((res) => console.log(res))
      .catch((error) => console.log());
  };
};

  • Related