前端的网络请求

前端的网络请求

ajax,fetch,封装一个简易版 axios

ajax

该例子从 get 和 post 做示例

步骤

  1. 实例化请求对象
var xhr = null;
if (!window.XMLHttpRequest) {
  try {
    // ie6
    xhr = new ActiveXObject("Msxm12.XMLHTTP");
  } catch (e) {
    // ie5或更早版本
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
  }
} else {
  xhr = new XMLHttpRequest();
}
  1. 进行连接
    get 方式传参,参数拼接在网址的?后面,key=value形式,多个参数用&分割。
    open 方法三个参数:方式,接口地址,true 表示异步请求,false 同步,默认是 true
// post
xhr.open("post", "http://127.0.0.1:3000", true);
// get
xhr.open("get", "http://127.0.0.1:3000?name=666&key=444", true);
  1. 设置请求头
    get 方式不用设置请求他,因为走的是地址栏传参,但是 post 需要设置,因为参数是在请求体里。
// json格式传参,最好用的,但是兼容性……
xhr.setRequestHeader("Content-Type", "application/json");
// form表单式传参,需要自己处理入参格式,兼容性好
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  1. 发送请求
    get 方式参数在地址栏拼接,但是 send 函数也要调用,因为它才是真正的发送请求;post 方式的参数在 send 里
// 该入参对应的请求头是application/json
xhr.send(JSON.stringify({ name: "宋宇", age: 23 }));
// 该入参对的请求头是application/x-www-form-urlencoded
xhr.send("name=9527&code=10086");
  1. 监听响应
// 设置返回值的数据类型
xhr.responseType = "json";
xhr.onreadystatechange = function () {
  // xhr.status 网络状态 xhr.readyState ajax的生命周期0-4
  if (xhr.status === 200 && xhr.readyState === 4) {
    console.log(xhr.response);
  }
};

fetch

【语法】

fetch(url, { method, body, headers: {'Content-Type', "application/json" } }).then(
      res => {
        // 如下两种解析方式二选一,一般最多的是用的json解析
        // 解析json
      return  res.json()
        // 解析文本
      return  res.text()
      }
    ).then(
      data => {
        console.log(data)
      }
    )

get

fetch("http://127.0.0.1:3000?name=555", { method: "get" })
  .then((res) => {
    // 使用json方法将二进制的数据流序列化
    return res.json();
  })
  .then((data) => {
    console.log(data);
  });

post

fetch("http://localhost:3000", {
  method: "post",
  body: JSON.stringify({ name: 9527, age: 23 }),
  headers: {
    "Content-Type": "application/json",
  },
  // body: 'name=9527&age=23',
  // headers: {
  //   "Content-Type": "application/x-www-form-urlencoded"
  // }
})
  .then((res) => res.json())
  .then((data) => {
    console.log(data);
  });

meaxios

开始封装,我的出发点只有一个,避免全局污染

class axios {
  constructor(url, method, data) {
    if (arguments.length === 0 || !url || !url.includes("http"))
      return Promise.resolve(false);
    if (!method) {
      this.method = "get";
    } else {
      this.method = method.toLocaleLowerCase();
    }

    // 入参数判断
    if (!data) {
      this.body = false;
    }

    // 根据请求方式不同处理不同的数据
    if (this.method === "post") {
      this.headers = {
        "Content-Type": "application/json",
      };
      this.body = data ? JSON.stringify(data) : false;
      this.options = {
        method: this.method,
        body: this.body,
        headers: this.headers,
      };
    } else if (this.method === "get") {
      // 如果用户传入的是对象 url?name=val
      if (typeof data === "object") {
        let d = "";
        for (let i of Object.entries(data)) {
          d += i[0] + "=" + i[1];
        }
        this.url = url + "?" + d;
      }
      // 如果用户传入的就是key=val&key=val

      // 如果用户传入的就是纯值:1
      this.options = {
        method: this.method,
      };
    } else {
    }

    // 最后返回一个promise
    return new Promise((resolve, reject) => {
      window
        .fetch(this.url, this.options)
        .then((res) => res.json())
        .then((res) => {
          resolve(res);
        });
    });
  }
}

// 使用
new axios("http://127.0.0.1:3000", "get", { name: "宋宇", age: "23" }).then(
  (res) => {
    console.log("得到了数据", res);
  }
);

结束语

我记录的只是基础的使用,实际上 ajax 也好 fetch 也罢,都还有很多强大的功能,比如 abort 终止请求方法的使用,ajax 的 load 事件里监听文件上传进度等。




如果你遇到了前端难题,或者需要一对一帮扶服务,请到淘宝搜索店铺:前端在线或扫下面二维码

  转载规则


《前端的网络请求》宋宇采用知识共享署名 4.0 国际许可协议进行许可。
  目录