# 安装

npm install axios

# 配置

src/utils/axios/index.js

/**
 * 请求拦截、错误统一处理
 */
import axios from 'axios'
import { message } from 'ant-design-vue'
const instance = axios.create({
    baseURL: 'http://localhost:8080',
    validateStatus: function (status) {
        // 此处决定请求响应 status 不满足该条件时进入 error 分支
        return status >= 200 && status < 300;
    },
    transformResponse: function (data) {
        console.log(data)
        return data;
    },
    headers: {
        'Content-Type': 'application/json;charset=utf-8'
    },
    timeout: 1000 * 5, // 超时时间,
    responseType: 'json',
    responseEncoding: 'utf8'
})
/**
 * 请求拦截器
 */
instance.interceptors.request.use(function (config) {
    // 每次发送请求之前判断是否存在 token,存在则添加到请求头中
    const token = ''
    token && (config.headers.token = token)
    return config;
}, function (error) {
    return Promise.reject(error);
});
/**
 * 响应拦截器
 */
instance.interceptors.response.use(function (response) {
    console.log(response)
    return response;
}, function (error) {
    console.log(error.response)
    if (error.response) {
        // 请求已经发出
        switch (error.response.status) {
            case 401: {
                console.log('未登录')
                // 跳转到登录页面
                message.error("未登录")
                break
            }
            case 403: {
                console.log('登录过期,请重新登录')
                // 清除当前 token
                // 进行提示并跳转到登录页面
                message.error("登录过期,请重新登录")
                break
            }
            case 404: {
                console.log('请求地址错误')
                message.error("请求地址错误")
                break
            }
            default: {
                console.log('其他错误')
            }
        }
    } else {
        // 断网、连接超时
        message.error("网络连接异常")
    }
    // 不进行 return axios 请求响应不会进入 catch 分支,但却会进入 then 分支,不过此时 then 分支的参数值是为空的
    // 返回后,catch 分支中可以获取 error 信息
    // 实际上,对于未成功的请求响应,因为已在拦截器进行处理,所以实际使用时不用进行 catch 操作
    return Promise.reject(error);
});
export default instance;

# vue3 全局属性设置

src/main.js

import axios from './utils/axios'
app.config.globalProperties.$axios = axios

# 使用

# setup 方法中

import {getCurrentInstance} from 'vue'
const $axios = getCurrentInstance().appContext.config.globalProperties.$axios

# methods 方法中

this.$axios