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