Vue3 + Vite + TS + Element-Plus + Pinia项目(5)对axios进行封装

1、在src文件夹下新建config文件夹后,新建baseURL.ts文件,用来配置http主链接

2、在src文件夹下新建http文件夹后,新建request.ts文件,内容如下

复制代码
import axios from "axios"
import { ElMessage } from 'element-plus'
import router from "../router/index.ts"
import {baseURL_dev} from '../config/baseURL.ts'
import useUser from '../store/user.ts'

const userStore=useUser()
const Service = axios.create({
    timeout:8000,
    baseURL:baseURL_dev,
    headers:{
        "Content-type":"application/json;charset=utf-8",
        "Authorization":""
    }
})
// 添加请求拦截器
Service.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    if (config.headers.Authorization == null ||  config.headers.Authorization== "") {
        config.headers.Authorization = "Bearer "+userStore.userInfo.token;
    }
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
Service.interceptors.response.use(function (response) {
    const data = response.data;
    if(data.code!=undefined)
    {
        if(data.code!=200 && data.code!=201){
            if(data.code==401)
            {
                userStore.clearUser();
                router.push('/')
                return data;
            }
            ElMessage.error(data.errorMsg||"服务器出错")          
            return data
        }
    }
    return data
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  });



// get请求
export const get = async (config:any)=>
{
    let ret = await Service({...config,method:"get",params:config.data})
    return ret
}

// post请求
export const post=async (config:any)=>{
    let ret = await Service({...config,method:"post",data:config.data})
    return ret
}


// put请求
export const put=async (config:any)=>{
    let ret = await Service({...config,method:"put",data:config.data})
    return ret
}

// delete请求
export const del=async (config:any)=>{
    let ret = await Service({...config,method:"delete"})
    return ret
}

3、配置api,新建api.ts

复制代码
import {post,get,put,del} from './request.ts'

//登录方法
export const loginApi=async (data: object)=>{ 

    let ret= post({
        url:"/Login/CheckLogin",
        data
    })
    //console.log(ret)
    return ret
}

// 获取信息
export const getOutPatientsApi=async (data: object)=>{ 
    let ret= get({
        url:`/Patient/GetOutPatients`,
        data
    })
    return ret
} 
// 更改患者信息
export const changePatientInfoApi=(data: object)=>{ 
    return put({
        url:`/Patient/ChangePatientInfo`,
        data
    })
} 

// 删除用户
export const userDeleteApi=(data: object)=>{ 
    return del({
        url:`/User/DeleteUserById/${data.userId}`
    })
} 

4、使用api

复制代码
import { getPatientsApi, addPatientApi, changePatientInfoApi } from "../../http/api";

 getPatientsApi(searchParams).then((res) => {
    if (res) {
      if (res.data) {
        // console.log("用户数据", res);
        data.patientList = res.data.dataList;
        data.total = res.data.totalCount;
      }
    }
  });
相关推荐
朱 欢 庆12 小时前
云服务器附件备份到本机内网服务器
运维·服务器·前端·经验分享
支支დ17 小时前
VO by Vercel 前端特定优势:为什么它是构建 AI 应用的新范式
前端·人工智能
香芋芋圆18 小时前
AI 冲击内卷之下,普通前端如何破局?WebGIS—— 低门槛突围赛道
前端·javascript·人工智能·学习·职场发展
INS_KF18 小时前
【编程笔记】成员函数中两个 const 的区别(const Data &getData() const;)
前端·javascript·笔记
宿67419 小时前
vue3-async
前端·javascript·vue.js
YXWik619 小时前
记录前端请求接口在浏览器请求响应的Preview和Response展示的一样的问题
前端
2501_9289962219 小时前
GPT-4o换DeepSeek迁移成本多少?中科热备解析API聚合平台技术账本
前端·数据库·人工智能
东风破_19 小时前
从跨域到 WebSocket:前端跨域方案、SSE 与双向实时通信详解
前端·后端
原则猫19 小时前
TS 类型工具
前端
excel20 小时前
Nuxt + Twin CSS 中宽度超过屏幕时底部出现空白的原因与解决方案
前端·javascript