一篇文章让你学会如何选择 JS HTTP 请求库

之前前端提到网络请求一般是指浏览器,但如今随着 Node.js、小程序的出现,网络请求再也不局限于浏览器。本文将带你了解不一样请求的原理,以及如何为项目选择合适的请求库。

1. 请求原理

1.1 浏览器

浏览器经过 XMLHttpRequest 对象实现 http 请求。javascript

远古时代 ie6 是借助 ActiveXObject 对象实现 http 请求,目前已无人使用,不考虑兼容。php

W3C 标准新提出的 Fecth API,基于 Promise 实现,相对 XMLHttpRequest 对象调用更方便,但旧浏览器不支持 Promise,须要对 Promise 进行 pollyfill。前端

  • XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open('get', url, true); 
xhr.send();
xhr.onreadystatechange = function() {
    if(xhr.readyState === 4 && xhr.status === 200 ) {
        let response = JSON.parse(xhr.responseText);
    }
}
  • Fetch
fetch(url)
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(e => console.log("error", e))

1.2 Node.js

Node.js 发布于 2009 年,是一个基于 Chrome V8 引擎的 JavaScript 运行环境,Node.js 的顶层对象是 global,不存在 window 对象,不能经过 XMLHttpRequest 对象实现 http 请求。java

Node.js 中经过引入 http/https/http2 模块实现 http 请求,下面为 http 模块实现的例子:node

const http = require('http');

const server = http.createServer((req, res) => {
  res.end('hello world');
});
server.on('clientError', (err, socket) => {
  socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);

1.3 React Native

React Native 是 Facebook 2015 开源跨平台移动应用开发工具。jquery

React Native 中已经内置了 XMLHttpRequest API,同时提供了和 web 标准一致的Fetch API,因此大部分在 web 端可使用的网络请求库在 React Native 中也可使用。ios

1.4 Weex

Weex 是 阿里 2016 开源跨平台移动应用开发工具。web

Weex 经过封装模块来调用原生功能,提供了 stream 模块来实现网络请求。ajax

1.5 小程序

2017 年微信小程序上线,随后各大平台都推出本身的小程序。npm

小程序因为要对 http 请求作参数校验、兼容各平台(iOS、Android)或版本问题,因此提供了一套属于本身的 API,不提供 window 对象。

下面为微信小程序和支付宝小程序的官网示例:

  • 微信小程序
wx.request({
  url: 'test.php', // 仅为示例,并不是真实的接口地址
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  success(res) {
    console.log(res.data)
  }
})
  • 支付宝小程序
my.httpRequest({
  url: 'http://httpbin.org/post',
  method: 'POST',
  data: {
    from: '支付宝',
    production: 'AlipayJSAPI',
  },
  dataType: 'json',
  success: function(res) {
    my.alert({content: 'success'});
  },
  fail: function(res) {
    my.alert({content: 'fail'});
  },
  complete: function(res) {
    my.hideLoading();
    my.alert({content: 'complete'});
  }
});

2. 请求库

从上文能够看出,平台间的请求方式存在各类差别,请求库就是为解决这种差别。下面为目前较火的请求库。

2.1 $.ajax(支持浏览器)

https://nodei.co/npm/jquery.png?downloads=true&downloadRank=true&stars=true

$.ajax 为 jQuery 对 XMLHttpRequest 对象进行兼容封装。

须要补充的是 React Native 可使用部分浏览器网络请求库,可是不能使用 jQuery,由于 jQuery 中还使用了不少浏览器中才有而 React Native 中没有的东西。

此外,如今使用框架的项目中咱们一般采用其余请求库,或者本身根据项目对 XMLHttpRequest 或 Fetch 进行封装,不会为了网络请求引入 jQuery。

2.2 Request(支持 Node.js)

https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true

Request 是对 Node.js 的 http/https 模块封装的 http 库。

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

2.3 SuperAgent(支持 Node.js)

https://nodei.co/npm/superagent.png?downloads=true&downloadRank=true&stars=true

SuperAgent 和 Request 相似,都是对 Node.js 的 http/https 模块封装的 http 库。

var request = require('superagent')
request
  .post('/api/pet')
  .send({ name: 'Manny', species: 'cat' })
  .set('X-API-Key', 'foobar')
  .set('Accept', 'application/json')
  .then(res => {
     alert('yay got ' + JSON.stringify(res.body));
  });

2.4 Axios(支持 React Native,Node,浏览器)

https://nodei.co/npm/axios.png?downloads=true&downloadRank=true&stars=true

Axios 是一个基于 promise 的 HTTP 请求库,能够用在浏览器和 Node.js 中。浏览器中使用 XMLHttpRequest,Node.js 中使用 http/https 模块。下面为请求示例:

axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

Vue 2.0 推荐使用 Axios 做为 Vue 的请求库。并且在 SSR 的时候咱们在服务端、客户端都须要请求,因此一般会选择 Axios。

2.5 Fly.js(支持 Node.js 、微信小程序 、Weex 、React Native 、Quick App 和浏览器)

https://nodei.co/npm/flyio.png?downloads=true&downloadRank=true&stars=true

Fly.js 是一个基于 promise 的 HTTP 请求库,能够用在Node.js 、微信小程序 、Weex 、React Native 、Quick App 和浏览器中,对上述平台都作了兼容。

fly.get('/user?id=133')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

除了 Fly.js,有些小程序开发框架自己提供网络请求库,对平台作了兼容,好比 Taro.request。

3. 总结

不一样请求库之间的 API、使用都会存在区别。项目开始时,根据须要兼容的平台选择合适的请求库,会大大减小之后代码重构的麻烦。

  • 本文首发于公众号,更多内容欢迎关注个人公众号: 阿夸漫谈
相关文章
相关标签/搜索