Home > Mobile >  ReactJs how to add interceptor in axios
ReactJs how to add interceptor in axios

Time:01-21

I've been working on this for hours, and I have no idea where did it go wrong. I want to have an axios interceptor for my ReactJs

this is my interceptor axiosHandler.js

import axios from "axios";

const axiosHandler = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
  headers: {
    Accept: "application/json",
  },
});

axiosHandler.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = "Bearer "   token;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

//axiosHandler.interceptors.response

export default axiosHandler;

And here is how I use the handler in my other component

import axiosHandler from "../services/axiosHandler";

const getData = async () => {
    await axiosHandler
      .get(`/path`)
      .then((response) => {
        //do something
      })
  };

And I get an error of below

services_axiosHandler__WEBPACK_IMPORTED_MODULE_0_.get is not a function

I've read many other solutions, but I can't find the difference as how it leads to the error of mine. Where do I put it wrong?

Thank you

CodePudding user response:

inside axios.index

import axios from "axios";
import { API_URL } from "../config/config";


const axiosHttp = axios.create({
  baseURL: `${API_URL}`,
});

axiosHttp.interceptors.request.use(
  (config) => {
    const token =  "Your Token here"
    return {
      ...config,
      headers: {
        ...(token !== null && { Authorization: `${token}` }),
        ...config.headers,
      },
    };
  },
  (error) => {
    return Promise.reject(error);
  }
);

axiosHttp.interceptors.response.use(
  (response) => {
    //const url = response.config.url;

    //setLocalStorageToken(token);
    return response;
  },
  (error) => {
    if (error.response.status === 401) {
      //(`unauthorized :)`);
      //localStorage.removeItem("persist:root");
      //removeLocalStorageToken
      //window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);

export default axiosHttp;

Then inside your API function use it like below

import axiosHttp from "./utils/axios"; 

const getData = async ()=>{
  try{
     const response = await axiosHttp.get('/path')
     return resposne;

  }
  catch(error){
     //handle error here...
  }

}

Last but not least, you shouldn't use await when using callback (then/catch)

  • Related