Axios is a popular JavaScript library used for making HTTP requests from web browsers and Node.js applications. It provides a simple and intuitive API to facilitate communication with RESTful APIs. In this post, I will cover how to integrate Axios in a React project.
instance.interceptors.request.use(function (config) { if (config.url === '/login') { return config; } // Do something before request is sent config.headers["Authorization"] = 'Bearer ' + Cookies.get(tokenKey); return config; }, function (error) { // Do something with request error returnPromise.reject(error); });
Add a response interceptor
Add content to axios.ts
instance.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data... return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error console.log('error:', error); if (error.response.status === 401) { Cookies.remove(tokenKey); // redirect to login page window.location.href = '/login'; returnPromise.reject(error); } else { alert(error.response.data.message) } });
The complete example of axios.ts
src/utils/axios.ts
import axios from"axios"; importCookiesfrom'js-cookie'; const baseURL = import.meta.env.VITE_API_BASE_URL; const tokenKey = import.meta.env.VITE_TOKEN_KEY; console.log('baseURL:', baseURL); const instance = axios.create({ baseURL: baseURL, timeout: 3000, headers: { 'Content-Type': 'application/json', } }); instance.interceptors.request.use(function (config) { if (config.url === '/login') { return config; } // Do something before request is sent config.headers["Authorization"] = 'Bearer ' + Cookies.get(tokenKey); return config; }, function (error) { // Do something with request error returnPromise.reject(error); }); instance.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data... return response; }, function (error) { // Any status codes that fall outside the range of 2xx cause this function to trigger // Do something with response error console.log('error:', error); if (error.response.status === 401) { Cookies.remove(tokenKey); // redirect to login page window.location.href = '/login'; returnPromise.reject(error); } else { alert(error.response.data.message) } }); exportdefault instance;