fetch|fetch 请求封装

// 接口请求封装 import 'whatwg-fetch'; let FetchData = https://www.it610.com/article/(method, url, param, headers=null) => { // 打开loading ...let newParam = null; if (method === 'GET' || method === 'get') newParam = null; else newParam = JSON.stringify(param); // 请求头信息 let defaultHeaders = { 'Content-Type': 'application/json', 'Accept-Charset': 'utf-8', }; let newHeaders = {...defaultHeaders, ...headers}; return new Promise((resolve, reject) => { fetch(url, { method: method, body: newParam, headers: newHeaders, }).then(res => { // 关闭loading...// 如果返回的状态为200,表示正常 if(res.status === 200) { return res.json(); } else { // 服务器端抛出的错误会在这里捕获 reject(res.statusText); } }).then(json => { // 如果返回 code=-1,则表示错误 if(json.code === -1) reject(json.message); else resolve(json); }).catch(error => { // 关闭loading Toast.clear(); // 其它错误会在这里获捕 reject(error); }); }); }; export default FetchData;

    推荐阅读