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;
}
}
});