Simple encapsulation of network requests (Axios) in Vue, including request interceptor and response interceptor
Introduction to axios
Axios is a promise-based network request library that can be used in browsers and node.js
Axios official Chinese documentation
characteristic
- Create XMLHttpRequests from the browser
- Create http request from node.js
- Support Promise API
- Intercept requests and responses
- Transform request and response data
- Cancel request
- Timeout processing
- Query parameter serialization supports nested item handling
- Automatically serialize the request body into:
JSON (application/json)
Multipart / FormData (multipart/form-data)
URL encoded form (application/x-www-form-urlencoded) - Convert HTML Form to JSON for request
- Automatically convert JSON data
- Get the request progress of the browser and node.js, and provide additional information (speed, remaining time)
- Set bandwidth limit for node.js
- Compatible with specification-compliant FormData and Blob (including node.js)
- Client supports defense against XSRF
Install
npm install axios;
Sample code
https.js
import axios from "axios";
// const token = localStorage.getItem("accessToken");
export const https = axios.create({
baseURL: "http://localhost:3000",
timeout: 15000,
headers: {
},
});
// 添加请求拦截器
https.interceptors.request.use(
(config) => {
// 在发送请求之前做些什么
// if (token) {
// config.headers.accessToken = `Bearer ${token}`;
// }
return config;
},
(error) => {
// 对请求错误做些什么
// console.log(error);
return Promise.reject(error);
}
);
// 添加响应拦截器
https.interceptors.response.use(
(response) => {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
// console.log(response);
if (response.status === 200) {
// console.log(Promise.resolve(response));
return Promise.resolve(response);
} else {
return Promise.reject(response);
}
// return response;
},
(error) => {
// 超出 2xx 范围的状态码都会触发该函数。
console.log(error);
// 对响应错误做点什么
return Promise.reject(error);
}
);
Introduced and used in Vue
import {
https } from "@/api/http";
//GET请求
// 写过的一个分页查询为例
https
.get("/display", {
params: {
pageSize: page.pageSize.value,
currentPage: page.currentPage.value,
},
})
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
// 另一种写法
https.get("/display?ID=12345")
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
//POST请求
https
.post("/display", {
id: id.value,
})
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});