在src 目录下 新建 api文件夹, 新建一个 baseApi.js
还有 pages文件夹下的每个页面的文件对应的 api文件
例如 home主页就建个 home.js
![](https://img.haomeiwen.com/i15697111/7ff55c7a674c9158.png)
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
})
网友评论