JS 发送 HTTP 请求方法封装

XMLHttpRequest 版本

function ajax(opts) {
  var xhr = new XMLHttpRequest(),
    type = opts.type || 'GET',
    url = opts.url,
    params = opts.data,
    dataType = opts.dataType || 'json';

  type = type.toUpperCase();

  if (type === 'GET') {
    params = (function(obj){
      var str = '';

      for(var prop in obj){
        str += prop + '=' + obj[prop] + '&'
      }
      str = str.slice(0, str.length - 1);
      return str;
    })(opts.data);
    url += url.indexOf('?') === -1 ? '?' + params : '&' + params;
  }

  xhr.open(type, url);

  if (opts.contentType) {
    xhr.setRequestHeader('Content-type', opts.contentType);
  }

  xhr.send(params ? params : null);

  //return promise
  return new Promise(function (resolve, reject) {
    //onload are executed just after the sync request is comple,
    //please use 'onreadystatechange' if need support IE9-
    xhr.onload = function () {
      if (xhr.status === 200) {
        var result;
        try {
          result = JSON.parse(xhr.response);
        } catch (e) {
          result = xhr.response;
        }
        resolve(result);
      } else {
        reject(xhr.response);
      }
    };
    
  });
}

axios 版本

import axios from 'axios';

export default function API(options) {
  return new Promise((resolve, reject) => {
    axios({
      method: options.method || 'GET',
      url: options.url,
      data: options.data,
      headers: options.headers,
    }).then(
      d => {
        let data = typeof d.data === 'string' ? JSON.parse(d.data) : d.data;
        if (data.success === true) {
          resolve(options.handleFn ? options.handleFn(data) : data);
        } else {
          let msg = data.message || data.msg;
          reject(msg);
        }
      },
      error => {
        reject(error.message);
      }
    );
  });
}

node 中使用 urllib

const urllib = require('urllib');
const _ = require('lodash');

export default function API(url, params) {
  const defaultParams = {
    method: 'GET',
    dataType: 'json',
    contentType: 'json',
    data: {}
  };

  const response = await urllib.curl(url, _.merge({}, defaultParams, params));
}

原文地址:https://www.cnblogs.com/everlose/p/12501202.html