配合 cookie
的模拟,可以实现和浏览器一样的请求体验。
使用方式
1 2 3 4
| import $http from '../plugins/http.js'
$http.get('/api', {key: value}).then(res => ...) $http.post('/api', {key: value}).then(res => ...)
|
原理解读 - http.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| import config from '../config'; import cookieUtil from './cookie';
const getResponse = function (url, data = {}, opt = {}) { opt.url = (/^http/i).test(url) ? url : `${config.api || ''}${url}`; opt.data = data; opt.header = Object.assign(opt.header || {}, { Cookie: cookieUtil.getAllString(), });
const reqPromise = new Promise((resolve, reject) => { const requestTask = wx.request(Object.assign(opt, { success(res) { const setCookieStr = res.header['Set-Cookie'] || res.header['set-cookie']; setCookieStr && cookieUtil.parseSetCookie(setCookieStr); if (res.statusCode === 200) { resolve(res.data); } else { reject(new Error('网络错误,请稍后再试')); } }, fail() { reject(new Error('网络错误,请稍后再试')); }, })); setTimeout(() => { requestTask.abort(); reject(new Error('网络超时,请稍后再试')); }, 10000); });
return reqPromise; };
const get = function (url, data = {}, opt = {}) { return getResponse(url, data, opt).then((result) => { if (result.code === 0) { return result.data; } throw new Error(result.msg || result.message); }); };
const post = function (url, data = {}, opt = {}) { opt.method = 'POST'; opt.header = opt.header || {}; opt.header['Content-Type'] = opt.header['Content-Type'] || opt.header['content-type'] || 'application/json'; return get(url, data, opt); };
export default { get, post, getResponse, };
|
全文完。