Nodejs sends the request

The following code refers to nodeJS 10.15.3. You are advised to install nodeJS 10.15.3 or later, which encapsulates the get, POST, and JSONP request modes

import https from 'https'
import http from 'http'
import qs from 'querystring'


const getReqType = url= > {
  return url.startsWith('https://')? https : http }export const getReq = (url, params, options = {}) = > (new Promise((resolve, reject) = > {
  let request = getReqType(url)
  let keys = Object.keys(params)
  url = keys.length ? (url + (url.indexOf('? ') > - 1 ? '&' : '? ') + qs.stringify(params).replace(/ \? $/g.' ')) : url
  request.get(url, options, res => {
    var data = ' '
    res.on('data', (chunk) => {
      data += chunk;
    })
    res.on('end', () => {
      resolve(data)
    })
  }).on('error', err => {
    reject(err)
  })
}))

export const postReq = (url, body, options = {}) = > (new Promise((resolve, reject) = > {
  let request = getReqType(url)
  let content = qs.stringify(body)
  options.headers = options.headers ? options.headers['content-type'] ? options.headers : {
    ...options.headers,
    'content-type': 'application/x-www-form-urlencoded'}, {'content-type': 'application/x-www-form-urlencoded'
  }
  options.headers['Content-Length'] = Buffer.byteLength(content, 'utf8')

  letreq = request.request(url, { ... options,method: 'POST',
  }, res => {
    res.setEncoding('utf8');
    var data = ' '
    res.on('data', (chunk) => {
      data += chunk
    })
    res.on('end', () => {
      resolve(data)
    })
  }).on('error', err => {
    reject(err)
  })
  req.write(qs.stringify(content))
  req.end()
}))

export const jsonp = async (url, params) => {
  let callback = '_cb'
  if (params.callback) {
    callback = params.callback
  }
  let res
  const data = awaitgetReq(url, { ... params, callback })eval(`function ${callback}(data){res=data}   ` + data)
  return res
}

export default {
  get: getReq,
  post: postReq,
  jsonp
}
Copy the code

A method is called

import request from './req'
async function getData() {
  const res = await request.get('http://localhost:3000/get', {
    name: 'shibin'
  })
}
getData()
Copy the code

Browser sends request

The following is encapsulated using ES5

var  _jpid = 0

function Request() {
  var util = {}
  util.get = util.GET = function(url, params, cb) {
    this._formatRequest(url, 'GET', params, db)
  }
  util.post = util.POST = function(url, data, cb) {
    this._formatRequest(url, 'POST', data, cb)
  }
  util._formatRequest = function(url, type, data, cb) {
    util.ajax({
      url: url,
      type: type,
      data: data,
      success: function(res) {
        cb(res)
      },
      error: function(err) {
        cb(' ', err)
      }
    })
  }
  util.ajax = function(opt) {
    var xhr = XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject
    var type = opt.type.toUpperCase(),
      data = opt.data,
      url = opt.url,
      dataArr = []
    for (var k in data) {
      if(typeof data[k] ! = ='undefined') {
        dataArr.push(k + '=' + data[k])
      }
    }
    if (type= = ='GET') {
      url = dataArr.length ? (url + (url.indexOf('? ') > 1?'&' : '? ') + dataArr.join('&')).replace(/\? $/g,' ') : url
      xhr.open(type, url, true)
      for (var k in opt.headers) {
        xhr.setRequestHeader(k, opt.headers)
      }
      xhr.send()
    } else if (type= = ='POST') {
      xhr.open(type, url, true)
      xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded')
      for (var k in opt.headers) {
        xhr.setRequestHeader(k, opt.headers)
      }
      xhr.send(dataArr.join('&'))}else if (type= = ="JSONP") {
      util.jsonp(opt)
    }
    xhr.onload = function() {
      var res = JSON.parse(xhr.responseText)
      if (xhr.status === 200 || xhr.status === 304) {
        if (opt.success && opt.success instanceof Function) {
          var res = JSON.parse(xhr.responseText)
          if (xhr.status === 200 || xhr.status === 304) {
            opt.success.call(xhr, res)
          } else {
            opt.error.call(xhr, res)
          }
        }
      } else {
        if (opt.error && opt.error instanceof Function) {
          opt.error.call(xhr, res)
        }
      }
    }
  }

  util.inQueryUrl = function(url, data) {
    if(! data) {return url
    }
    var str = url + '? '
    for (var k in data) {
      var item = k + '=' + data[k] + '&'
      str += item
    }
    str = str.slice(0, str.length - 1)
    return str
  }
  util.jsonp = function(opt) {
    var callbackName = opt.jsonp || ((opt.data && opt.data.callback) ? opt.data.callback : '_jp' + _jpid++)
    opt.data.callback = callbackName
    var head = document.getElementsByTagName('head')[0]
    var data = formatParams(opt.data)
    var script = document.createElement('script')
    head.appendChild(script)
    window[callbackName] = function(json) {
      head.removeChild(script);
      clearTimeout(script.timer);
      window[callbackName] = null;
      if (opt.success && opt.success instanceof Function) {
        opt.success.call(window, json)
      }
    }
    script.src = opt.url + '? ' + data
    if (opt.time) {
      script.timer = setTimeout(function() {
        window[callbackName] = null;
        head.removeChild(script);
        opt.error && opt.error({
          message: 'timeout'
        });
      }, time)
    }
  }
  return util
}

function formatParams(data) {
  var arr = [];
  for (var name in data) {
    arr.push(encodeURIComponent(name) + '='+ encodeURIComponent(data[name])); }; // Add a random number to prevent caching arr.push('v=' + random());
  return arr.join('&'); } // Get a random numberfunction random() {
  return Math.floor(Math.random() * 10000 + 500);
}
Copy the code

A method is called

var $=new Request()
$.ajax({
  url:'http://localhost:3000/post'.type:'post'.data: {name:'shibin'
  },
  success:function(res){
    console.log(res)
  },
  error:function(err){
    console.log(err);
  }
})

 $.get('http://localhost:3000/get', {
    name: 'shibin'
 }, function(res, err) {
    if (res) {
     console.log(res)
   } else {
     console.log(err); }})Copy the code

The following is based on ES6 encapsulation

var __jpid = 0

class Request {
  get(url, params) {
    return new Promise((resolve, reject) = > {
      this._formatRequest(url, 'GET', params, resolve)
    })
  }
  post(url, params) {
    return new Promise((resolve, reject) = > {
      this._formatRequest(url, 'POST', params, resolve)
    })
  }
  _formatRequest(url, type, data, resolve) {
    this.ajax({
      url: url,
      type: type,
      data: data
    }).then(res= > {
      resolve(res)
    })
  }
  ajax(opt) {
    return new Promise((resolve, reject) = > {
      var xhr = XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject
      var type = opt.type.toUpperCase(),
        data = opt.data,
        url = opt.url,
        dataArr = []
      for (var k in data) {
        if (typeofdata[k] ! = ='undefined') {
          dataArr.push(k + '=' + data[k])
        }
      }
      if (type === 'GET') {
        url = dataArr.length ? (url + (url.indexOf('? ') > - 1 ? '&' : '? ') + dataArr.join('&')).replace(/ \? $/g.' ') : url
        xhr.open(type, url, true)
        for (var k in opt.headers) {
          xhr.setRequestHeader(k, opt.headers)
        }
        xhr.send()
      } else if (type === 'POST') {
        xhr.open(type, url, true)
        xhr.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded')
        for (var k in opt.headers) {
          xhr.setRequestHeader(k, opt.headers)
        }
        xhr.send(dataArr.join('&'))}else if (type === 'JSONP') {
        this.jsonp(opt, reject, resolve)
      }
      xhr.onload = function() {
        var res = JSON.parse(xhr.responseText)
        if (xhr.status === 200 || xhr.status === 304) {
          resolve(res)
          if (opt.success && opt.success instanceof Function) {
            opt.success.call(xhr, res)
          }
        } else {
          reject(res)
          if (opt.error && opt.error instanceof Function) {
            opt.error.call(xhr, res)

          }
        }
      }
    })

  }
  jsonp(opt) {
    return new Promise((resolve, reject) = > {
      // var callbackName = opt.jsonp;
      var callbackName = opt.jsonp || ((opt.data && opt.data.callback) ? opt.data.callback : '_jp' + __jpid++)
      opt.data.callback = callbackName
      var head = document.getElementsByTagName('head') [0]
      var data = formatParams(opt.data);
      var script = document.createElement('script')
      head.appendChild(script)
      window[callbackName] = function(json) {
        head.removeChild(script);
        clearTimeout(script.timer);
        window[callbackName] = null;
        resolve(json)
        if (opt.success && opt.success instanceof Function) {
          opt.success.call(window, json)
        }
      }
      script.src = opt.url + '? ' + data
      if (opt.time) {
        script.timer = setTimeout(function() {
          window[callbackName] = null;
          head.removeChild(script);
          reject({
            message: 'timeout'
          })
          opt.error && opt.error({
            message: 'timeout'
          });
        }, time)
      }
    })
  }
}

function formatParams(data) {
  var arr = [];
  for (var name in data) {
    arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
  };
  // Add a random number to prevent caching
  arr.push('v=' + random());
  return arr.join('&');
}
// Get a random number
function random() {
  return Math.floor(Math.random() * 10000 + 500);
}
Copy the code

A method is called

var $=new Request()
$.ajax({
  url:'http://localhost:3000/post'.type:'post'.data: {name:'shibin'
  }
}).then(res= > {
    console.log(res)
})
Copy the code