0

Using axios I am trying to set default header auth token for all the request. But its not seeting up by default and for any other api call 'Authorization' is not setting up in header.

this is UseHttp.js which is a common file

import axios from 'axios';
const axiosClient = axios.create({
    headers: {
        'Content-type': 'application/json',
        'Accept': 'application/json',
    }
});
const UseHttp = (requestConfig) => {
    return axiosClient({
        url: requestConfig.url,
        method: requestConfig.method || 'GET',
        data: requestConfig.body && JSON.stringify(requestConfig.body)
    }).then((response) => {
        if (response.status == 200) {
            return response.data;
        } else {
            throw new Error(response.data.message);
        }
    }).then((data) => {
        return data.data;
    }).catch((error) => {
        return error.message;
    });
};
export const setAuthHeader = (header) => {
    
    axiosClient.defaults.headers.common['Authorization'] = header;}
export default UseHttp;

After login I am setting the header like this

import {USER} from './Url';
import UseHttp, {setAuthHeader} from './UseHttp';
/* eslint-disable */
export const LoginApi = async (values) => {
    const requestOptions = {
        user_name: values.username,
        password: values.password
    }
    try {
        let res = await UseHttp({ url : USER.login, method:'POST', body: requestOptions});
        setAuthHeader(res.token);
        return res;
    } catch (err) {
        return err;
    }
}

But when I call any other Api header for Authorization is not set there where CountryApi.js is

   import UseHttp from './UseHttp';
   import {LANDING} from './Url';
    
    export const countryList = () => UseHttp({ url: LANDING.get_country_list });

and Country.js is this

import {countryList} from '../../../api/CountryApi';
useEffect(() => {
    countryList().then((res) => {
        setallData(res)
        
    });
}, [locale]) 
Ron
  • 394
  • 1
  • 12
  • 24
  • see if one of the answers here help: https://stackoverflow.com/questions/40988238/sending-the-bearer-token-with-axios?rq=1 – Dejan Janjušević Sep 02 '22 at 07:15
  • Why don't you try using interceptors https://axios-http.com/docs/interceptors. Interceptors solved this exact issue for me. – Dazly Gonsalves Sep 02 '22 at 07:22
  • DejanJanjušević but in my above code in every api call axiosClient get hit but its not calling "setAuthHeader " and my auth token is set in easy-peasy store . how to pass them here every time . – Ron Sep 02 '22 at 07:43
  • @DazlyGonsalves how to set my auth token in interceptors . I have very less idea on this. Can you modify my code and repost – Ron Sep 02 '22 at 07:47

1 Answers1

0

This is a basic implementation of how you can use interceptors to modify the request before it's sent and append the token to the header if it's stored in local storage.

import Axios from "axios";

const axios = Axios.create({
        headers: {
            'Content-type': 'application/json',
            'Accept': 'application/json',
        }
    });
    
    axios.interceptors.request.use((config) => {
      const token = localStorage.getItem("token");
      if (token) {
        config.headers!.Authorization = `Bearer ${token}`;
      }
    
      return config;
    });