Vue3 封装 Axios
封装 Axios
封装
ts
// utils/request.ts
import axios from 'axios';
const instance = axios.create({
baseURL: 'http://127.0.0.1:7000',
timeout: 1000
});
// 请求拦截
instance.interceptors.request.use((config) => {
// 请求发送前添加上 token
const token = localStorage.getItem('token');
if (token) {
config.headers.common['Authorization'] = 'Bearer ' + token;
}
});
// 响应拦截
instance.interceptors.response.use((config) => {
(config) => {
return config;
},
(error) => {
let message = '未知错误,请联系管理员!';
if (error && error.response) {
switch (error.response.status) {
case 302:
message = '接口重定向了!';
break;
case 400:
message = '参数不正确!';
break;
case 401:
message = '您未登录,请先登录!';
localStorage.removeItem('token');
localStorage.removeItem('user');
break;
case 403:
message = '您没有权限操作!';
break;
case 404:
message = `请求地址出错: ${error.response.config.url}`;
break;
case 408:
message = '请求超时!';
break;
case 409:
message = '系统已存在相同数据!';
break;
case 500:
message = '服务器内部错误!';
break;
case 501:
message = '服务未实现!';
break;
case 502:
message = '网关错误!';
break;
case 503:
message = '服务不可用!';
break;
case 504:
message = '服务暂时无法访问,请稍后再试!';
break;
case 505:
message = 'HTTP 版本不受支持!';
break;
default:
message = '未知错误,请联系管理员!';
break;
}
}
return Promise.reject(message);
}
});
export default instance;
发送请求
ts
// api/user.ts
import instance from '../utils/request';
export const login = (username: string, password: string) => {
return instance.post('/user/login', {
username,
password
});
};
获取 data
js
// Login.vue
import { login } from '../api/user';
const { data: res } = await login(username, password);
全局挂载(不推荐)
挂载
在
main.ts
引入 axiostsimport axios from 'axios'; import { AxiosStatic } from 'axios';
配置 axios 默认地址
tsconst app = createApp(App); axios.defaults.baseURL = 'http://127.0.0.1:7000'; app.config.globalProperties.$http = axios;
声明 axios 类型
tsdeclare module '@vue/runtime-core' { interface ComponentCustomProperties { $http: AxiosStatic; } }
在 setup 中调用
导入
getCurrentInstance
与ComponentInternalInstance
tsimport { ComponentInternalInstance, getCurrentInstance } from 'vue';
解构赋值出
proxy
tsconst { proxy } = getCurrentInstance() as ComponentInternalInstance;
通过
proxy
访问$http
tsproxy?.$http('');
获取 data
ts
const login = async () => {
const { data: res } = (await proxy?.$http.post('/login', {
username: username.value,
password: password.value
})) as AxiosResponse<any>; // 为结果添加断言来解决data报错
};
预览: