二次封装axios

import axios from "axios";
import { ElMessage } from "element-plus";

const request = axios.create({
    baseURL: "http://127.0.0.1:3000/api",
    timeout: 5000,
});

request.interceptors.request.use((config) => {
    // config.headers['Authorization'] = 'Bearer ' + token;
    return config;
});

request.interceptors.response.use(
    (response) => {
        return response.data;
    },
    (error) => {
        const statusCode = error.code;
        let message = "";
        switch (statusCode) {
            case 401:
                message = "Token expires";
                break;
            case 403:
                message = "Unauthorized access";
                break;
            case 404:
                message = "Request address error";
                break;
            case 500:
                message = "Backend error";
                break;
        }
        ElMessage.error(message);
        return Promise.reject(error);
    }
);

export default request;
posted @ 2024-03-27 23:23  惊朝  阅读(8)  评论(0编辑  收藏  举报