XMLHttpRequest接口封装函数

312 阅读1分钟

经常要通过API接口与第三方进行交互,于是做了一个最基础的XMLHttpRequest接口封装函数。

const url = 'http://localhost:8080';

//api接口统一调用函数
//path,string, 接口路径
//params, string, 参数
//method, string, 请求方法
//headers, object array, 请求头
//callback, function, 回调函数
function commonAPI(path, params, method, headers, callback){
  let xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")
  xhr.open(method, url + path, true);
  if(typeof headers == "object" && headers.length > 0){
      for(let i = 0; i < headers.length; i++){
          xhr.setRequestHeader(headers[i].name,headers[i].content)
      }
  }
  xhr.onreadystatechange = function(){
      if (xhr.readyState == 4) {
           if (xhr.status == 200) {
              callback(xhr.responseText);
           } else {
              callback('{"error":"ok"}');
           }
      }
  };
  params = params.length == 0? null: params;
  try{
      xhr.send(params);
  } catch(e){
      callback('{"error":"ok"}');
  }
  
}

实际调用案例如下:

//设备请求头
let headers = [{"name":"Content-Type", "content":"application/json"}];

commonAPI('/api/tenant/devices?pageSize=20&page=1', '', 'GET', headers, getDeviceList);

function getDeviceList(res){
    let msg = JSON.parse(res);
    console.log(msg);
}