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,
    });
};
相关推荐
ZC跨境爬虫2 分钟前
跟着 MDN 学JavaScript day_6:JavaScript 中的基础数学——数字与运算符
开发语言·前端·javascript·学习·ecmascript
copyer_xyf2 分钟前
Python 迭代器与生成器
前端·后端·python
KaMeidebaby8 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl8 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl9 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
nuIl9 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl9 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf9 小时前
Python 异常处理
前端·后端·python
sugar__salt9 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
MageGojo9 小时前
随机文案模块怎么做?从接口封装到前端展示的完整实现思路
javascript·前端开发·api接口·后端开发·随机文案