微信小程序打夯之旅(三):Http封裝

配合 cookie 的模擬,能夠實現和瀏覽器同樣的請求體驗。javascript

使用方式

import $http from '../plugins/http.js'

$http.get('/api', {key: value}).then(res => ...)
$http.post('/api', {key: value}).then(res => ...)
複製代碼

原理解讀 - http.js

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;
  // 手動設置cookie
  opt.header = Object.assign(opt.header || {}, {
    Cookie: cookieUtil.getAllString(),
  });

  const reqPromise = new Promise((resolve, reject) => {
    const requestTask = wx.request(Object.assign(opt, {  // eslint-disable-line
      success(res) {
        // 手動模擬set-cookie
        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('網絡錯誤,請稍後再試'));
      },
    }));
    // 10秒超時
    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,
};

複製代碼
相關文章
相關標籤/搜索