引言在Vue.js项目中,Axios是一个常用的HTTP客户端,用于发送异步HTTP请求。然而,随着项目规模的扩大,直接使用Axios可能会导致代码冗余、难以维护。本文将介绍如何深度封装Axios,实...
在Vue.js项目中,Axios是一个常用的HTTP客户端,用于发送异步HTTP请求。然而,随着项目规模的扩大,直接使用Axios可能会导致代码冗余、难以维护。本文将介绍如何深度封装Axios,实现API接口的管理与优化。
首先,我们需要创建一个Axios实例,并配置基础参数。
import axios from 'axios';
const service = axios.create({ baseURL: 'https://api.example.com', // 基础URL timeout: 5000, // 请求超时时间 withCredentials: true, // 允许跨域携带cookie
});
export default service;在请求拦截器中,我们可以添加token等参数。
service.interceptors.request.use( config => { // 添加token等参数 config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`; return config; }, error => { return Promise.reject(error); }
);在响应拦截器中,我们可以处理数据格式、错误提示等。
service.interceptors.response.use( response => { // 处理数据格式 return response.data; }, error => { // 处理错误提示 if (error.response) { const { status, data } = error.response; console.error(`Error ${status}: ${data.message}`); } else { console.error('Error:', error.message); } return Promise.reject(error); }
);接下来,我们可以封装一些常用的API接口。
// 封装登录接口
export function login(username, password) { return service.post('/login', { username, password });
}
// 封装用户信息接口
export function getUserInfo() { return service.get('/user/info');
}在Vue组件中,我们可以直接调用封装后的API接口。
<template> <div> <button @click="login">登录</button> <button @click="getUserInfo">获取用户信息</button> </div>
</template>
<script>
import { login, getUserInfo } from '@/api/user';
export default { methods: { async login() { try { const { data } = await login('username', 'password'); console.log(data); } catch (error) { console.error(error); } }, async getUserInfo() { try { const { data } = await getUserInfo(); console.log(data); } catch (error) { console.error(error); } } }
};
</script>通过深度封装Axios,我们可以轻松实现API接口的管理与优化。封装后的API接口具有统一管理、错误处理、请求拦截和响应拦截等优点,有助于提高Vue.js项目的可维护性和可扩展性。