Basic configuration of axios, request interceptor and response interceptor

Posted by nariman on Mon, 03 Jan 2022 22:14:17 +0100

1: Basic introduction

In actual projects, axios needs to be encapsulated once to uniformly configure the basic configuration of axios, request interceptor, response interceptor, etc;

2: Basic configuration

We can use axios Create ([config]) to create an instance with axios general configuration. The following are common configuration items:

import axios from "axios";

const request = axios.create({
	baseURL:"xxx",  // Basic address. For requests that do not start with http or https, this address will be spliced in front
	timeout:20000,  // Timeout. If no reply is received from the server after this time, an error will be reported. The unit is milliseconds
	method:"post",  // The default request method is get. You can set the default method here to other request methods
	headers:{},     //Request header configuration
})
export default request;

In this way, we can use request by introducing it into other files. This is only the basic configuration, which can be overwritten when used.

3: Request interceptor

The request interceptor can be set here when sending a request using this instance, which is usually used to carry functions such as token;

import axios from "axios";

const request = axios.create({
	baseURL:"xxx",  
	timeout:20000, 
})

// request interceptor 
request.interceptors.request.use(
	(config)=>{
		if(config.url !== "/sys/login"){   // Determine whether the request is a login interface
			config.headers.token = sessionStorage.getItem("token"); // If it is not a login interface, set a token in the request header
		}
		return config; // The configuration object is returned. If it is not returned, the request will not be sent
	},
	(error)=>{
		return Promise.reject(error);
	}
)
export default request;

Use request interceptors. request. The use() function can configure the request interceptor. This function receives two parameters, the first is the successful callback function and the other is the failed callback function. The successful callback function has one parameter, as shown in the following figure:

You can use these attributes to determine whether to continue sending the request.

4: Response interceptor

After receiving the data returned by the server, the response interceptor can be set here

import axios from "axios";

const request = axios.create({
	baseURL:"xxx",  
	timeout:20000, 
})

// Response interceptor
request.interceptors.response.use(
	(res)=>{
		let code = res.data.code  // Get the status code returned by the backend
		if(code===200){           // success
			return res.data.data  // Return the data inside. When using this axios, what you get is what you return here
		}else{
			return res.data   
		}
	},
	(error)=>{
		return Promise.reject(error);
	}
)

export default request;

Use request interceptors. response. The use() function can configure the response interceptor. This function also has two parameters. The first is the successful callback function and the second is the failed callback function. There is a parameter in the successful callback function, This parameter is the data returned from the back end (Note: this data is encapsulated by axios, so we usually directly take the data inside). The returned res is as follows:

Here, we can agree on the status code with the back-end and carry out corresponding processing through the status code, such as returning data normally if successful, jumping to the login page if the token fails, etc; It should also be noted that the back end generally handles errors, so the sent request rarely directly reports an error (obtained through catch), but tells you an error through the status code (generally 500). However, if the axios request succeeds, it only returns an error message, which will still appear in. then.

5: Summary

Here is the complete code

import axios from "axios";
import router from "Routing file address"; // Get route

const request = axios.create({
	baseURL:"xxx",  
	timeout:20000, 
})

// request interceptor 
request.interceptors.request.use(
	(config)=>{
		if(config.url !== "/sys/login"){   // Determine whether the request is a login interface
			config.headers.token = sessionStorage.getItem("token"); // If it is not a login interface, set a token in the request header
		}
		return config; // The configuration object is returned. If it is not returned, the request will not be sent
	},
	(error)=>{
		return Promise.reject(error);
	}
)

// Response interceptor
request.interceptors.response.use(
	(res)=>{
		let code = res.data.code  // Get the status code returned by the backend
		if(code===200){           // success
			return res.data.data  // Return the data inside. When using this axios, what you get is what you return here
		}else if (code == 401) {  // token failure
      		router.push("/login");  // Jump to landing page
    	}else{
			return res.data   
		}
	},
	(error)=>{
		return Promise.reject(error);
	}
)

export default request;

Topics: Javascript Front-end