axios 高级封装
阅读原文时间:2023年07月09日阅读:2

import axios from 'axios';
import qs from 'qs';
const Unit = {
async getApi(ajaxCfg){
let data = await axios.get(ajaxCfg.url,{params:ajaxCfg.cfg},
{
headers: ajaxCfg.headers
})
return data;
},
async getApi2(url,cfg,headers){
let data = await axios.get(url,{params:cfg},
{
headers: headers
})
return data;
},
async postApi(url,cfg,headers){
let fd = new FormData();
for(let key in cfg){
fd.append(key, cfg[key]);
}
let data = await axios.post(url,cfg,
{
headers: headers
})
return data;
},
async putApi(url,cfg,headers){
let data = await axios.put(url,qs.stringify(cfg),{
headers: {
'Content-Type':'application/x-www-form-urlencoded',
}
})
return data;
},
async postApi2(url,cfg,headers){
let data = await axios.post(url,cfg,
{
headers: headers
})
return data;
},
async postApi3(url,cfg,headers){
let data = await axios.post(url,qs.stringify(cfg),{
headers: {
'Content-Type':'application/x-www-form-urlencoded',
}
})
return data;
},
async delApi(url,cfg,headers){
let data = await axios.delete(url,{params:cfg},{
headers: headers
})
return data;
},
async requestApi(cfg,headers,file){
let fd = new FormData();
fd.append('param', JSON.stringify(cfg));
if(file){
// 上传证明
if(file.length){
for(let i=0,len=file.length;i{
            console.log(res.data)
        })
        // // // get one
        const id = 33;
        Unit.getApi2(`/users/${id}`,{},{}).then((res)=>{
            console.log(res.data)
        })
        //更新
        Unit.putApi(`/users/${id}`,{name:1,age:32},{}).then((res)=>{
            console.log(res.data)
        })
        //删除ok
        // let _id = 33;
        // Unit.delApi(`/users/${_id}`,{},{}).then((res)=>{
        //     console.log(res.data)
        // })
        // 插入数据
        Unit.postApi2('/users',{name:4,age:32},{}).then((res)=>{
            console.log(res.data)
        })

app.use(
      '/users',createProxyMiddleware({
        target: 'http://127.0.0.1:7001/',
        changeOrigin: true,
      })
    );

本人CSDN本章地址:https://blog.csdn.net/lastone1212/article/details/117366246

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章