项目源码-Vue3项目11-整合Axios

Last Updated on 2025年1月13日 by hangzi

整合Axios

1、安装依赖

pnpm add axios

2、创建工具类request.js

工具类简单封装,新建工具类src/utils/request.js,内容如下:

import axios from "axios";
import {toLogin} from "@/router";

const TOKEN_KEY = "accessToken";
const baseUrl = "/demo";

const service = axios.create({
    baseURL: baseUrl,
    timeout: 50000,
    headers: {"Content-Type": "application/json;charset=utf-8"},
})

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const accessToken = localStorage.getItem(TOKEN_KEY);
        if (accessToken) {
            config.headers.Authorization = accessToken;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        // 检查配置的响应类型是否为二进制类型('blob' 或 'arraybuffer'), 如果是,直接返回响应对象
        if (response.config.responseType === "blob" ||
            response.config.responseType === "arraybuffer") {
            return response;
        }

        const {code, data, msg} = response.data;
        if (code === 200) {
            return data;
        }
        ElMessage.error(msg || "系统出错");
        return Promise.reject(new Error(msg || "Error"));
    },
    (error) => {
        // 异常处理
        if (error.response.data) {
            const {code, msg} = error.response.data;
            if (code === 401) {
                ElMessageBox.confirm("当前页面已失效,请重新登录", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    new Promise((resolve) => {
                        localStorage.setItem(TOKEN_KEY, "");
                        toLogin();
                        resolve();
                    }).then(() => {
                        location.reload();
                    });
                });
            } else {
                ElMessage.error(msg || "系统出错");
            }
        }
        return Promise.reject(error.message);
    }
);

// 导出 axios 实例
export default service;

3、在业务API接口中,使用工具类request.js

工具类使用,使用在src/api/auth.js中,内容如下:

import http from "@/utils/request"

class AuthAPI {
    /**
     * 登录
     */
    static login(data) {
        const formData = new FormData();
        formData.append("username", data.username);
        formData.append("password", data.password);
        return http({
            url: "/auth/login",
            method: "post",
            data: formData,
            headers: {
                "Content-Type": "multipart/form-data"
            }
        });
    }
}

export default AuthAPI;

4、在页面中,使用业务API接口

src/views/login/index.vue中,使用业务API接口,内容如下:

<template>
  <h1>登录页</h1>

  <el-form :model="form" label-width="80px">
    <el-form-item>
      <template #label>
        <span>*</span> 用户名
      </template>
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item>
      <template #label>
        <span>*</span> 密码
      </template>
      <el-input v-model="form.password" />
    </el-form-item>
    <el-button type="primary" @click="onSubmit">登录</el-button>
  </el-form>

</template>

<script setup>
import AuthAPI from "@/api/auth.js";

const form = reactive({
  username: '',
  password: ''
});

function handleLoginData() {
  //处理数据
  console.log("处理数据")
}
//登录
function onSubmit() {
  AuthAPI.login(form)
      .then(handleLoginData)
      .catch((error) => {
        ElMessage.error(error || "系统出错");
      })
}
</script>

<style lang="less" scoped>

.el-form-item span {
  color: @error-color;
}

</style>

项目Demo源码:https://github.com/hangzhi7/Vue3-Demo


关注微信公众号『编程与读书

第一时间了解最新网络动态
关注博主不迷路~