Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

axios request and response intercepters

import axios, { AxiosResponse } from "axios";
import { useNavigate } from "react-router-dom";

export const axiosInstance = axios.create({
  baseURL: "http://localhost:3001/api",
});

const responseIntercepter = (response: AxiosResponse) => {
  return response;
};
const requestIntercepter = (config) => {
  config.headers.Authorization =
    "Bearer " + localStorage.getItem("accessToken");
  return config;
};

axiosInstance.interceptors.request.use(requestIntercepter);
axiosInstance.interceptors.response.use(responseIntercepter, (err) => {
  const expectedErrors =
    err.response && err.response.status >= 400 && err.response.status < 500;
  if (!expectedErrors) {
    console.log(err, "err");
    return;
  } else {
    if (err.response.status === 401) {
      localStorage.removeItem("accessToken");
      localStorage.removeItem("userId");
      const navigate = useNavigate();
      navigate("/login");
    }
    return Promise.reject(err);
  }
});
Comment

PREVIOUS NEXT
Code Example
Javascript :: constant values javascript 
Javascript :: replace all javascript 
Javascript :: extend javascript 
Javascript :: return object list in find js 
Javascript :: match string in array javascript 
Javascript :: if window width jquery then display a div at scroll 
Javascript :: how to dekete from string all "," js 
Javascript :: rich editor react 
Javascript :: javaScript getHours() Method 
Javascript :: babel start command nodejs 
Javascript :: javascript find in nested array 
Javascript :: how to add eslint to react project 
Javascript :: index of row jquery 
Javascript :: node convert string to hash 
Javascript :: how to comments in json file 
Javascript :: react native dimensions 
Javascript :: object destructuring 
Javascript :: javascript read text file from url 
Javascript :: Type writer in react 
Javascript :: array concat in javascript 
Javascript :: datatables cdn 
Javascript :: search string for character javascript 
Javascript :: json stands for 
Javascript :: send sms using twilio in node 
Javascript :: js .touppercase 
Javascript :: flatten nested object js 
Javascript :: map method in react 
Javascript :: how to get first element of an array in javascript 
Javascript :: jquery class selector 
Javascript :: js .substring 
ADD CONTENT
Topic
Content
Source link
Name
9+1 =