vue对axios进行二次封装

前言

在Vue中,对Axios进行二次封装可以提高代码的可重用性和可维护性。通过封装,我们可以将请求的配置、错误处理和拦截器等逻辑集中到一个地方,方便后续的修改和扩展。此外,封装Axios还可以简化代码,减少重复的请求配置,提高开发效率。因此,对Axios进行二次封装是Vue开发中一个非常实用的技巧。

1、教程步骤

1.npm或cnpm下载axios或

npm:

复制代码
npm install axios -g

cnpm:

复制代码
cnpm install axios -g

2.http.js

可以在src目录下建立http包,并在包内创建index.js,添加如下配置

javascript 复制代码
import Axios from "axios";
import {MessageBox, Message} from 'element-ui'
import store from '../store/index'
import {getToken} from '@/utils/auth';

// 创建axios实例
const service = Axios.create({
    baseURL: process.env.VUE_APP_BASE_API, //URL地址   环境变量文件 .env.development
    timeout: 5000,//超时
    withCredentials: false,  //跨域时若要发生cookie,需要设置该选项
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        // if (store.getters.token) {
            // 设置令牌请求头
            config.headers['authorization'] = getToken()?getToken():null;
        // }
        return config
    },
    error => {
        return Promise.reject(error)
    }
);



// 相应拦截
service.interceptors.response.use(
    // 通过自定义code 判定响应状态 也可以通过HTTP状态码判断
    response => {
        const res = response.data;
        // code 不为0 则判断为一个错误
        if (res.code !== 20000) {
            Message({
                message: res.message || "Error",
                type: 'error',
                duration: 5 * 1000
            });
            // 假设 10008 非法令牌  10012 其他客户端已经登陆
            if (res.code === 40001 || res.code === 10012) {
                // 重新登陆
                MessageBox.confirm(
                    '登陆状态异常,请重新登陆',
                    "确认登陆信息",
                    {
                        confirmButtonText: '重新登陆',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    store.dispatch('user/resetToken')
                        .then(() => {
                            location.reload()
                        })
                })
            }

            return Promise.reject(new Error(res.message || 'Error'));

        } else {
            return res;
        }
    },
    error => {
        if (error.message.includes('timeout')) {  // 如果错误信息中包含'timeout',则认为是连接超时
            Message.error("网络超时");
        }else{
            Message.error("网络超时");
        }

    }
);

export default service;

3.使用

可以自己将不同模块请求进行封装,在其他地方直接调用即可

javascript 复制代码
import service from "../index";

export const login = (params) => {
    return service({
        url: "/user/login",
        method: "post",
        data:params,
    });
};
相关推荐
铁皮饭盒11 分钟前
bun直接tsx,优雅!
javascript·后端
Csvn2 小时前
Monorepo 迁移血泪史:从 Multi-Repo 到 Turborepo,这 3 个坑我帮你踩完了
前端
星栈2 小时前
Dioxus 多页面怎么做:`dioxus-router`、嵌套路由、`Outlet` 和页面组织,一篇给你讲顺
前端·rust·前端框架
用户987409238872 小时前
用 Remotion + edge-tts 打造中文教学视频全自动流水线
前端
风骏时光牛马2 小时前
Less前端工程化实战:变量混合器与项目样式分层落地
前端
假如让我当三天老蒯2 小时前
Options API(选项式 API) 和 Composition API(组合式 API)
前端·vue.js·面试
SameX2 小时前
iOS 独立开发实践:用 MapKit + 像素渲染实现 Citywalk 轨迹地图 App「雁过留痕」
前端
_柳青杨2 小时前
一文吃透 Node.js 事件循环:从原理到 Node 20+ 重大变更
javascript·后端
skyey2 小时前
页面加载时,深色模式闪白的问题解决
前端
IT_陈寒3 小时前
Java 并行流把我坑惨了,这6小时加班值了
前端·人工智能·后端