react 对axios简单封装

2022-09-08  本文已影响0人  南土酱

在src 目录下 新建 api文件夹, 新建一个 baseApi.js
还有 pages文件夹下的每个页面的文件对应的 api文件

例如 home主页就建个 home.js
home
baseAPI.js
import axios from "axios";

const client = axios.create({
  baseURL: "http://localhost:8080/api",
  //withCredentials: true,
});
export default client;

这里前后端分离项目 要配置的 withCredentials 可以看我另一篇文章
👉前端携带 sessionID Access-Control-Allow-Credentials 跨域 - 简书 (jianshu.com)

home.js

//async/await 写法:
import client from "./baseAPI"
async function getDailyAdd(){
    const response = await client.get("/home/dailyAdd");
    return response['data']
    
}
//promise 写法
async function getMonAdd(){
    return new Promise((resolve,rej)=>{
        client.get("/home/monAdd").then((res)=>{
            resolve(res.data)
        }).catch((v)=>{
            rej(v)
        })
    })
}
export {getDailyAdd,getMonAdd}

如此便可以调用接口了

 let result = getMonAdd()
        result .then((v) => {
          do something
  })
上一篇 下一篇

猜你喜欢

热点阅读