接口封装 get post
发布于 6 年前 作者 s123rr 1557 次浏览 来自 客户端测试

export const baseURL = “https://cnodejs.org/api/v1”; export const getURL = (url, params) => { let paramsArray = []; Object.keys(params).forEach(key => paramsArray.push(key + “=” + params[key])); if (url.search(/?/) === -1) { url += “?” + paramsArray.join("&"); } else { url += “&” + paramsArray.join("&"); } return url; }; export const getData = async (url, obj) => { url = obj ? getURL(url, obj) : url; //转换为需要的url let res = await fetch(baseURL + url, { method: “GET” }); let json = res.json(); return json; }; //通过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; };

回到顶部