Steps for Vue to encapsulate Axios requests and interceptors
- 2021-08-16 23:06:59
- OfStack
PS: This code is written on top of the basic vue project built by vue-cli3: vue create my-project
axios is an http library based on promise, which can be used in browsers and node. js, and is also the http library officially recommended by vue.
axios is very easy to use, one of which is that its interceptor is 10 points powerful. We can set interceptors for requests and responses. For example, the request interceptor can add token to each request, which is convenient to maintain after unified 1 processing. The response interceptor can do layer 1 operations after receiving the response, such as judging login status and authorization according to the status code.
When I was a beginner, I often wrote axios data requests in various component methods. However, practice has proved that if the project interface changes, it will be troublesome and difficult to maintain parameters such as url address, so it is necessary to encapsulate axios and manage the interface system 1.
First, of course, we need to install axios by using the command npm install axios--save.
1. Create a new function file
Create a new axios directory under the src directory, and then create two files, axios-request. js and axios-api. js,
Among them, aixos-request. js is used to encapsulate axios, and axios-api. js is used to manage the interface.
2. Encapsulate axios
axios-request. The code for js is as follows:
import axios from "axios";
import { Message } from "element-ui";
// Create 1 A axios Instances
const axiosService = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
timeout: 5000 // Set the timeout time to 5s
});
// request Interceptor ==> Processing request parameters
axiosService.interceptors.request.use(
config => {
// You can do something before sending a request
// Such as the processing of request parameters, in the headers Carrying in token Wait
return config;
}, error => {
// Error processing request
console.log(error); // for debug
Promise.reject(error);
}
);
// respone Interceptor ==> Processing the response
axiosService.interceptors.response.use(
response => {
const res = response.data;
// If the custom return code is not equal to 200, Go back 1 Errors
if (res.code !== 200) {
return Promise.reject(new Error(res.message || "Error"))
} else {
return res;
}
}, error => {
// Judge error Adj. status Code and inform the user of the corresponding information
let text = "";
let err = JSON.parse(JSON.stringify(error));
if (err.response.status) {
switch (error.response.status) {
case 400:
text = " Request error (400) Please reapply ";
break;
case 401:
text = " Login error (401) Please log in again ";
return this.$router.replace("/login");
case 403:
text = " Access denied (403)";
break;
case 404:
text = " Request error (404)";
break;
case 408:
text = " Request timeout (408)";
break;
case 500:
text = " Server error (500) Please restart the software or switch the function page! ";
break;
case 501:
text = " Service not implemented (501)";
break;
case 502:
text = " Network error (502)";
break;
case 503:
text = " Service unavailable (503)";
break;
case 504:
text = " Network timeout (504)";
break;
case 505:
text = "HTTP Version is not supported (505)";
break;
default:
text = " Network connection error ";
}
} else {
text = " Failed to connect to server , Please exit and try again !";
}
Message({
showClose: true,
message: text,
type: "error"
});
return Promise.reject(error);
}
);
// What will be written axios The instance is exposed
export default axiosService;
3. Manage the interface in a unified way
The code for axios-api. js is as follows:
import axiosService from "./axios-request"; // From axios-request.js Internal introduction axiosService
// Below is POST Form
export const userLogin = data => {
return axiosService({
url: "/xxxx/user/xxxx", // Write according to the actual interface address
method: "post",
data
});
};
// Below is GET Form
export const userInfo = params => {
return axiosService({
url: "/xxxx/user/xxxx", // Write according to the actual interface address
method: "get",
params
});
};
Note here that the post parameter is placed in data, and the get parameter is placed in params!
4. Use the written interface within the component
Use in components:
The following is a simulated login interface. The code is not rigorous, and only demonstrates the general usage:
<script>
import {userLogin} from "@/axios/axios-api"; // Introducing login interface function
export default {
name: "login",
components: {},
methods: {
async login() {
let username = this.username;
let password = this.password;
let params = {
username: username,
password: password
};
if (!username || !password) {
alert(" The account number or password cannot be blank ");
} else {
if (username.length < 51 && password.length < 51) {
let res = await userLogin(params);
console.log(res);
} else {
alert(" Account or password input characters cannot exceed 50 Bit ");
}
}
}
}
};
</script>
In the above code, we used async await, which is a new feature of ES7. The specific usage can be viewed on Google or MDN.
STEP 5 Summarize
Of course, it is also possible not to manage the interface system 1, but only to encapsulate axios, and then write asynchronous request functions in the component.
The above is the individual in the previous study, the use of encapsulation, if there are any mistakes, please leave a message to correct.
The above is the Vue encapsulation Axios request and interceptor steps in detail, more information about Vue encapsulation please pay attention to other related articles on this site!