import WuhuBase from "../WuhuBase"; import Log from "../Log"; import AjaxFetchOption from "../../interface/AjaxFetchOption"; import IUserProfileData from "../../interface/IUserProfileData"; export default class FetchUtils extends WuhuBase { className = 'FetchUtils'; /** * 包装jquery ajax 异步返回string * @param url * @param method */ public ajax(url: string, method: 'GET' | 'POST'): Promise { return new Promise((res, rej) => { $.ajax({ method: method, url: url, success: function (data) { res(data) }, error: function (e) { rej(e) } }); }); } /** * jquery ajax 方法发送的 xhr, 头部中带有 X-Requested-With: XMLHttpRequest * return fetch * @param opt * @param opt.url 必输 * @param opt.referrer 默认: / * @param opt.method POST|GET 必输 * @param opt.body ? */ public ajaxFetch(opt: AjaxFetchOption) { let { url, referrer = '/', method, body = null } = opt; let req_params: RequestInit = { headers: { 'X-Requested-With': 'XMLHttpRequest' }, referrer, method, }; if (method === 'POST') { req_params.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; req_params.body = body; } return window.fetch(url, req_params); } public fetchText(url: string, init: RequestInit = null): Promise { return new Promise((resolve, reject) => window.fetch(url, init) .then(res => res.text()) .then(t => resolve(t)) .catch(err => { Log.error('fetchText出错了', err); reject(err); }) ); } public getProfile(uid: string): Promise { return new Promise((resolve, reject) => { this.ajaxFetch({ url: window.addRFC('https://www.torn.com/profiles.php?step=getProfileData&XID=' + uid), method: 'GET' }).then((o) => { o.json().then((res) => { resolve(res); }).catch(e => { Log.error('[ProfileHelper] JSON解析错误: ', e.message, '错误堆栈: ', e.stack); reject(e); }); }).catch(e => { Log.error('[ProfileHelper] 网络错误: ', e.message, '错误堆栈: ', e.stack); reject(e); }); }); } }