1. 安装axios 和 js-cookie
npm i axios js-cookie @types/js-cookie -S
2. 在src目录下创建plugins文件夹,在里面创建cookie.ts 封装一下js-cookie
import Cookies from 'js-cookie';
const TokenKey = 'token'
const RefreshTokenKey = 'refresh-token'
export function getToken() {
return Cookies.get(TokenKey)
}
export function getTokenKey() {
return TokenKey
}
export function getRefreshTokenKey() {
return RefreshTokenKey
}
export function setToken(token: any) {
return Cookies.set(TokenKey, token)
}
export function getRefreshToken() {
return Cookies.get(RefreshTokenKey)
}
export function setRefreshToken(refreshToken: any) {
return Cookies.set(RefreshTokenKey, refreshToken)
}
export function removeToken() {
Cookies.remove(TokenKey)
Cookies.remove(RefreshTokenKey)
}
3. 在src目录下创建http文件夹,在里面创建拦截器配置文件interceptors.ts
因为就简单的写了一个例子,所以所有报错信息都是使用
console.error();
来返回 后面可以自己使用组件库的弹框修改一下返回样式即可
// 首先引入axios和上一步封装的cookie方法
import axios, { AxiosInstance } from "axios";
import {
setToken,
setRefreshToken,
getToken,
getTokenKey,
getRefreshToken,
getRefreshTokenKey,
removeToken,
} from "../plugins/cookie";
export class Interceptors {
instance: AxiosInstance;
constructor() {
this.instance = axios.create({
baseURL: "/api",
timeout: 10000,
});
}
// 初始化拦截器
init() {
// 请求接口拦截器
this.instance.interceptors.request.use(
(config) => {
// 判断一下是否有cookie 如果有的话则把cookie放入请求头中
if (getToken()) {
config.headers[getTokenKey()] = getToken();
config.headers[getRefreshTokenKey()] = getRefreshToken();
}
return config;
},
(err) => {
console.error(err);
}
);
// 响应拦截器
this.instance.interceptors.response.use(
(response) => {
const res = response.data;
if (!response.status.toString().startsWith("2") || res.code === -1) {
// 如果状态码不是2开头或者接口code返回-1 则是返回错误信息
console.error("系统错误,请检查API是否正常!");
return;
}
if (res.code !== 0) {
if (res.code === -3) {
console.error("登录过期");
removeToken();
} else {
if (res.msg) {
console.error(res.msg);
}
}
return Promise.resolve(res);
} else {
// 返回成功则把token存储一下
const headers = response.headers;
const token = headers.token;
const refresh_token = headers["refresh-token"];
if (token && refresh_token) {
setToken(token);
setRefreshToken(refresh_token);
}
return res;
}
},
(error) => {
if (error.message === "Request failed with status code 500") {
console.error("系统错误,请检查API是否正常!");
return;
}
let code = -110;
if (error && error.response && error.response.status) {
code = error.response.status;
// 登陆过期
if (code === 401 || code === -3) {
removeToken();
}
} else {
console.error(error.message);
}
const err = { errCode: -110, errMsg: error.message || "Error" };
return Promise.resolve(err);
}
);
}
// 返回一下
getInterceptors() {
return this.instance;
}
}
4. 拦截器封装好了就简单封装一下axios 在http文件夹下创建index.ts
import { AxiosPromise, AxiosResponse } from "axios";
import { Interceptors } from "./interceptors";
// 请求配置
export class HttpServer {
axios: any;
// 获取axios实例
constructor() {
this.axios = new Interceptors().getInterceptors();
}
// 简单封装一下方法
request(config: any): AxiosPromise {
return new Promise((resolve, reject) => {
this.axios(config).then((res: AxiosResponse) => {
resolve(res);
}).catch((err: any) => {
reject(err)
});
});
}
}
const http = new HttpServer()
export default http
5. 把封装好的axios挂在到vue上 在之前的plugins文件夹下面新建axios.ts文件
个人习惯把插件都放在plugins文件夹下面
import { App } from "vue";
import http from "../http";
import { AxiosInstance } from "axios";
declare module "@vue/runtime-core" {
interface ComponentCustomProperties {
$axios?: AxiosInstance;
}
}
export const axiosPlugin = {
install(app: App): void {
app.config.globalProperties.$axios = http;
},
};
export default axiosPlugin
6.最后在main.ts里面引入
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import { axiosPlugin } from './plugins/axios';
const app = createApp(App)
app.use(store).use(router).use(axiosPlugin).mount("#app")
使用方法
- 在ts文件使用
import http from "../http/index";
function userLogin(data: any) {
return http.request({
url: "/user/login",
method: "post",
data
})
}
- 在vue文件使用
<script lang="ts">
import { getCurrentInstance } from "vue"
...
// 使用getCurrentInstance方法获取当前vdom实例
const axios = getCurrentInstance()?.appContext.config.globalProperties.$axios
axios.request({
url: '/user/login',
method: 'post',
data: login
})
...
</script>