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,
    });
};
相关推荐
贺今宵1 分钟前
安装better-sqlite3报错electron-vite
javascript·sql·sqlite·sqlite3
GIS之路15 分钟前
GIS 数据转换:使用 GDAL 将 GeoJSON 转换为 Shp 数据
前端
2501_9444460025 分钟前
Flutter&OpenHarmony文件夹管理功能实现
android·javascript·flutter
朴shu1 小时前
Luckysheet 远程搜索下拉 控件开发 : 揭秘二开全流程
前端
MediaTea2 小时前
Python:模块 __dict__ 详解
开发语言·前端·数据库·python
字节跳动开源2 小时前
Midscene v1.0 发布 - 视觉驱动,UI 自动化体验跃迁
前端·人工智能·客户端
光影少年3 小时前
三维前端需要会哪些东西
前端·webgl
王林不想说话3 小时前
React自定义Hooks
前端·react.js·typescript
颜酱3 小时前
滑动窗口详解:原理+分类+场景+模板+例题(视频贼清晰)
javascript
heyCHEEMS3 小时前
Uni-app 性能天坑:为什么 v-if 删不掉 DOM 节点
前端