import Loading from '../components/Loading'; /** * 检查HTTP请求状态 */ function checkStatus(response) { console.log('res1', response); if (response.status >= 200 && response.status < 300) { return response; } const error = new Error(response.statusText); error.response = response; throw error; } /** * 将Response内容转为JSON格式 */ function parseJSON(response) { Loading.hide(); return response.json(); } /** * 统一拦截接口返回数据的状态,提示错误消息 */ function checkAPIDatas(data) { console.log('data', data); if (!data.success) { const code = data; } Loading.hide(); return data; } function checkAPIError(err) { console.log('err', err); // const code = err.response.code; // const status = err.response.status; // const { url, type, oStatus, statusText } = err.response; // Message.error(`地址:${url} 类型:${type} 状态:${oStatus} 信息:${statusText}`, 10); Loading.hide(); return { err }; } /** * Requests a URL, returning a promise. * @param {string} url The URL we want to request * @param {object} [options] The options we want to pass to "fetch" * @return {object} An object containing either "data" or "err" */ const request = async (url, options) => { Loading.show(); const file_uid = await getuid(); if (options) { const method = options.method.toUpperCase(); // switch(method){ // case 'POST': // options.headers = { // 'Accept': 'application/json', // 'Content-Type': '"Content-Type": "application/json', // "uid": 'c2e13090a563447c8744a8c03171d1db', // 'token': await storage.load({ // key: 'token' // }) // }; // break; // case 'PUT': // options.headers = { // 'Accept': 'application/json', // 'Content-Type': 'application/x-www-form-urlencoded', // "uid": 'c2e13090a563447c8744a8c03171d1db', // // 'token': await storage.load({ // // key: 'token' // // }) // }; // break; // default: // options.headers = { // 'token': await storage.load({ // key: 'token' // }) // }; // break; // // } // const token = await storage.load({ // key: 'token' // }); options.headers = { Accept: 'application/json', 'Content-Type': 'application/json', uid: file_uid // 'token': token? token : null }; if (method === 'POST' || method === 'PATCH' || method === 'DELETE' || method === 'PUT') { options.body = JSON.stringify(options.body); } // else { // options.headers = { // // token: await storage.load({ // // key: "token" // // }) // }; // } } console.log('options', options); return fetch(url, options).then(checkStatus).then(parseJSON).then(checkAPIDatas).catch(checkAPIError); }; async function getuid() { const uid = await storage .load({ key: 'userInfo' }) .catch((error) => { return ''; }); if (uid === '') { return ''; } return JSON.parse(uid).uid; } export default request;