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;
      }
    }
  });
相关推荐
葡萄城技术团队6 小时前
1000 人协同压测的环境瓶颈排查:CPU 争用与 Wi\-Fi
前端
excel7 小时前
Marked 与 Markdown 有什么区别?该怎么选?
前端
Da Da 泓8 小时前
五子棋 Web 端测试用例报告
前端·网络·websocket·网络协议·测试用例·项目
zxcvb1539 小时前
远程查看本地文档:一条轻量 Web 文件服务的工程化链路
前端·远程查看文档
niucloud-admin9 小时前
NIUCLOUD PHP SAAS上门家政使用文档:城市管理
java·前端·php
程序员大阳9 小时前
副队长JavaScript教程(50)-DOM:网页开发的起点
javascript·dom·es·节点·概念·document·关系
北岛贰9 小时前
啵啵音乐迎来全新升级!
前端
hkNaruto11 小时前
【AI】基于大模型的AI游戏地图生成、控制方案:AI Native Game Harness 迁移操作手册
前端·人工智能·游戏
IT_陈寒12 小时前
Java序列化踩坑记:对象循环引用让我加班两小时
前端·人工智能·后端
Acro12 小时前
快给macOS 上的Grok Bot换一套皮肤
前端