vue实现http拦截
Vue 中实现 HTTP 拦截
在 Vue 中,通常通过 axios 库实现 HTTP 请求拦截。以下是具体实现方法:
安装 axios
通过 npm 或 yarn 安装 axios:
npm install axios
或
yarn add axios
创建 axios 实例并设置拦截器
在项目中创建一个单独的文件(如 http.js)来配置 axios 实例和拦截器:
import axios from 'axios';
const http = axios.create({
baseURL: 'https://api.example.com', // 设置基础 URL
timeout: 5000, // 设置超时时间
});
// 请求拦截器
http.interceptors.request.use(
(config) => {
// 在发送请求之前做些什么
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 响应拦截器
http.interceptors.response.use(
(response) => {
// 对响应数据做点什么
return response.data;
},
(error) => {
// 对响应错误做点什么
if (error.response) {
switch (error.response.status) {
case 401:
// 处理未授权情况
break;
case 404:
// 处理未找到资源情况
break;
default:
// 其他错误处理
}
}
return Promise.reject(error);
}
);
export default http;
在 Vue 组件中使用
在 Vue 组件中导入配置好的 axios 实例并使用:
import http from './http';
export default {
methods: {
fetchData() {
http.get('/data')
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
},
},
};
全局挂载 axios
如果需要全局使用,可以在 main.js 中挂载到 Vue 原型上:
import Vue from 'vue';
import http from './http';
Vue.prototype.$http = http;
之后在组件中可以直接使用:
this.$http.get('/data')
.then(response => {
console.log(response);
});
注意事项
- 拦截器的顺序很重要,先添加的拦截器会后执行。
- 确保在请求拦截器中返回
config对象,否则请求无法发送。 - 响应拦截器中可以根据业务需求统一处理错误,如 token 过期跳转登录页。
通过以上方法,可以在 Vue 项目中实现 HTTP 请求和响应的拦截,统一处理授权、错误等情况。







