//在util包下新建fetchData.js
const baseURL = "https://cnodejs.org/api/v1";
//封装的GET请求
export const getData = async (url, data) => {
let api = baseURL + url + "?";
if (data) {
for (key in data) {
api += key + "=" + data[key] + "&";
}
}
api = api.substr(0, api.length - 1);
let res = await fetch(api);
res = await res.json();
return res;
};
//通过post获取数据,url是接口地址,obj是发送给后台的数据对象
export const postData = async (url, obj) => {
let res = await fetch(baseURL + url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(obj)
});
let json = await res.json();
return json;
};
网友评论