js简单的网络请求封装

nodejs发送请求

下面代码参考的nodejs的版本10.15.3,建议安装10.15.3或更高的版本,简单的封装了getpostjsonp三种请求方式

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')

  let req = 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 = await getReq(url, { ...params,
    callback
  })
  eval(`function ${callback}(data){res=data}   ` + data)
  return res
}

export default {
  get: getReq,
  post: postReq,
  jsonp
}
复制代码

调用方法

import request from './req'
async function getData() {
  const res = await request.get('http://localhost:3000/get', {
    name: 'shibin'
  })
}
getData()
复制代码

浏览器发送请求

下面是使用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: '超时'
        });
      }, time)
    }
  }
  return util
}

function formatParams(data) {
  var arr = [];
  for (var name in data) {
    arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
  };
  // 添加一个随机数,防止缓存
  arr.push('v=' + random());
  return arr.join('&');
}
// 获取随机数
function random() {
  return Math.floor(Math.random() * 10000 + 500);
}
复制代码

调用方法

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);
   }
})
复制代码

下面是基于es6封装的

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 (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') {
        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: '超时'
          })
          opt.error && opt.error({
            message: '超时'
          });
        }, time)
      }
    })
  }
}

function formatParams(data) {
  var arr = [];
  for (var name in data) {
    arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
  };
  // 添加一个随机数,防止缓存
  arr.push('v=' + random());
  return arr.join('&');
}
// 获取随机数
function random() {
  return Math.floor(Math.random() * 10000 + 500);
}
复制代码

调用方法

var $=new Request()
$.ajax({
  url:'http://localhost:3000/post',
  type:'post',
  data:{
    name:'shibin'
  }
}).then(res => {
    console.log(res)
})
复制代码

转载于:https://juejin.im/post/5c997e7a6fb9a070c6189441

你可能感兴趣的:(js简单的网络请求封装)