Encapsulating Axios in a Vue Project: Installation, Configuration, and Request Handling
This guide explains how to install Axios, set up a reusable HTTP module in a Vue project, configure environment‑specific base URLs, define request timeouts and headers, and implement request and response interceptors along with simple get/post wrapper functions.
Axios is a promise‑based HTTP library that works in browsers and Node.js, offering features such as request/response interception, request cancellation, JSON transformation, and XSRF protection, making it a preferred choice over vue‑resource for Vue applications.
Install the library with the command:
npm install axios; // 安装axiosIn a src/request/http.js file, import the necessary modules:
import axios from 'axios'; // 引入axios
import QS from 'qs'; // 用于序列化 POST 数据
import { Toast } from 'vant'; // 可替换为其他 UI 组件Configure the base URL according to the current environment:
if (process.env.NODE_ENV == 'development') {
axios.defaults.baseURL = 'https://www.正式.com';
} else if (process.env.NODE_ENV == 'debug') {
axios.defaults.baseURL = 'https://www.测试.com';
} else if (process.env.NODE_ENV == 'production') {
axios.defaults.baseURL = 'https://www.生产.com';
}Set a global request timeout (e.g., 10 seconds):
axios.defaults.timeout = 10000;Create a custom axios instance with specific request headers:
const service = axios.create({
header: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});Implement a request interceptor to manage a loading mask, add a pending request counter, and automatically attach authentication and timestamp parameters to every request:
// 请求拦截器
service.interceptors.request.use(request => {
if (!request.headers['No-Request-Loading']) {
pendingCount++;
}
if (pendingCount) { addMask(); }
const auth = md5('qwerty_mailTo_123456');
const _time = +new Date();
if (request.method === 'post' && !request.params) {
request.data = { ...request.data, auth, _time };
} else {
request.params = { ...request.params, auth, _time };
}
return request;
}, error => Promise.reject(error));Implement a response interceptor to hide the loading mask, handle empty responses, and provide unified error handling based on the backend’s error codes:
// 响应拦截器
service.interceptors.response.use(response => {
if (pendingCount) { pendingCount--; }
if (!pendingCount) { removeMask(); }
if (!response || !response.data) {
ui.Message({ message: '服务器返回空', type: 'error', offset: 60 });
}
if (response.data.errno !== 2000) {
ui.Message({ message: response.data.errmsg, type: 'error', offset: 60 });
}
return response;
}, error => {
removeMask();
const status = error.response.status;
ui.Message({ message: '网络异常,错误码:' + status, type: 'error', offset: 60 });
return Promise.reject(error);
});Finally, wrap the most common HTTP methods into simple utility functions. The get function accepts a URL and a params object, returns a promise that resolves with the server response, while the post function also serializes the payload using the configured Content-Type header.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.