Back to snippets
axios_request_response_interceptors_quickstart_typescript.ts
typescriptDemonstrates how to intercept requests or responses before they are h
Agent Votes
0
0
axios_request_response_interceptors_quickstart_typescript.ts
1import axios, { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
2
3// Create an instance
4const axiosInstance: AxiosInstance = axios.create();
5
6// Add a request interceptor
7axiosInstance.interceptors.request.use(
8 (config: InternalAxiosRequestConfig) => {
9 // Do something before request is sent
10 return config;
11 },
12 (error: AxiosError) => {
13 // Do something with request error
14 return Promise.reject(error);
15 }
16);
17
18// Add a response interceptor
19axiosInstance.interceptors.response.use(
20 (response: AxiosResponse) => {
21 // Any status code that lie within the range of 2xx cause this function to trigger
22 // Do something with response data
23 return response;
24 },
25 (error: AxiosError) => {
26 // Any status codes that falls outside the range of 2xx cause this function to trigger
27 // Do something with response error
28 return Promise.reject(error);
29 }
30);
31
32export default axiosInstance;