Dependency Installation
npm install axios qsOrganize the networking layer by creating a dedicated service module. Within src/services/, generate httpClient.js for Axios configuration and apiRegistry.js for centralizing request routes.
Environment Configuration and Global Defaults
Dynamically assign the base URL based on the Node environment. Establish a timeout threshold to prevent hanging requests, and define the default Content-Type for POST payloads.
import axios from 'axios';
import querystring from 'qs';
import store from '@/store';
import router from '@/router';
import { Notify } from 'vant';
const envUrls = {
development: 'https://dev.api.example.com',
debug: 'https://staging.api.example.com',
production: 'https://api.example.com'
};
axios.defaults.baseURL = envUrls[process.env.NODE_ENV] || '';
axios.defaults.timeout = 15000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';Request Interception
Intercept outgoing requests to inject authentication credentials. A token retrieved from the Vuex store is attached to the Authorization header, ensuring secured endpoints receive valid credentials without manual configuration on individual calls.
axios.interceptors.request.use(
(config) => {
const accessToken = store.getters['auth/token'];
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`;
}
return config;
},
(error) => Promise.reject(error)
);Response Interception
Intercept incoming responses to handle successful payloads and uniform error handling. HTTP errors trigger specific side effects, such as redirecting unauthenticated users or clearing expired sessions.
const handleAuthError = () => {
localStorage.removeItem('accessToken');
store.commit('auth/clearSession');
router.replace({ path: '/auth/login', query: { next: router.currentRoute.fullPath } });
};
const errorHandlers = {
401: () => handleAuthError(),
403: () => {
Notify({ message: 'Session expired. Please log in again.', duration: 1500 });
setTimeout(() => handleAuthError(), 1500);
},
404: () => Notify({ message: 'Resource not found.', duration: 2000 })
};
axios.interceptors.response.use(
(response) => (response.status === 200 ? Promise.resolve(response) : Promise.reject(response)),
(error) => {
const { status, data } = error.response;
const handler = errorHandlers[status];
if (handler) {
handler();
} else {
Notify({ message: data.message || 'An unexpected error occurred', duration: 2000 });
}
return Promise.reject(error.response);
}
);Abstracting HTTP Methods
Create wrapper functions for GET and POST requests to streamline data fetching and submission. The POST wrapper serializes the payload using the qs module to ensure compatibility with form-encoded requirements.
export const retrieveData = (endpoint, params) => {
return axios.get(endpoint, { params })
.then((res) => res.data)
.catch((err) => { throw err; });
};
export const sendData = (endpoint, payload) => {
return axios.post(endpoint, querystring.stringify(payload))
.then((res) => res.data)
.catch((err) => { throw err; });
};