/** * 使用es6-fetch发送http请求,不兼容旧版浏览器 * 替换方案可选axios之类的库 */ import { Message } from 'view-ui-plus' class HttpRequest { constructor(apiRoot){ this.apiRoot = apiRoot } get(url) { return new Promise((resolve, reject) => { try { const apiUrl = this.getUrl(url) fetch(apiUrl).then(res => { if (res.ok) return res.json() else { let err = JSON.stringify({ type: res.type, status: res.status, statusText: res.statusText }) Message.error({ content: `调用${url}接口失败,` + err, duration: 10 }); reject(err); } }).then(res => { if (res.err_code === 0) resolve(res.result); else reject(`code=${res.err_code},` + res.err_msg); }).catch(err => { reject(`调用${url}接口失败,` + err); }); } catch (err) { reject(err); } }); } post(url, data) { return new Promise((resolve, reject) => { try { const apiUrl = this.getUrl(url) fetch(apiUrl, { method: 'POST', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json', }, }).then(res => { if (res.ok) return res.json() else { let err = JSON.stringify({ type: res.type, status: res.status, statusText: res.statusText }) Message.error({ content: `调用${url}接口失败,` + err, duration: 10 }); reject(err); } }).then(res => { if (res.err_code === 0) resolve(res.result); else reject(`code=${res.err_code},` + res.err_msg); // resolve(res); }).catch(err => { reject(`调用${url}接口失败,` + err) }) } catch (err) { reject(err); } }) } getUrl(url) { return `${this.apiRoot}/${url}`; } } export default HttpRequest;