TAY
笔记 · · 阅读 157

vue3 请求拦截器 响应拦截器

axiosService.js

import axios from "axios";
import { useAuth } from "@/stores/auth";
import { useToast } from "vue-toastification";

const toast = useToast()
const axiosInstance = axios.create({
    baseURL: import.meta.env.VITE_API_URL + "/api",
});

// 请求拦截器
axiosInstance.interceptors.request.use(
    function (config) {
        const auth = useAuth();
        config.headers.common["Authorization"] = `Bearer ${auth?._token}`;
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);

// 响应拦截器
axiosInstance.interceptors.response.use((res) => {
        return res;
    },(err) => {
        if (err.response && err.code == 'ERR_NETWORK') {
            toast.error('['+err.config.url+'] '+err.message);
        }
        return Promise.reject(err);
    }
);

export default axiosInstance;
目录