详解在Node.js中发起HTTP请求的5种方法(2)

与Axios类似, SuperAgent 是另一个流行的库,主要用于浏览器中的Ajax请求,但也适用于Node.js。使用以下命令安装SuperAgent :

npm install superagent@3.5.2

SuperAgent最酷的地方是能进行链式调用,你可以把其它函数链到像 query() 这样的请求上,并且添加参数。在前面的例子中我们都是手动添加它们。请注意 SuperAgent 是怎样提供这种功能的:

const superagent = require('superagent'); superagent.get('https://api.nasa.gov/planetary/apod') .query({ api_key: 'DEMO_KEY', date: '2017-08-02' }) .end((err, res) => { if (err) { return console.log(err); } console.log(res.body.url); console.log(res.body.explanation); });

和axios一样,你也不用自己解析去JSON响应,这非常酷。

Got

如果你想用一个更轻量级的库,Got是另外一个选择。它也可用于Twilio Functions

再来一遍,实用npm安装Got:

npm install got@7.1.0

和Axios一样,Got也能同Promises一起很好的工作。下面的代码做的事情和前面的例子一样:

const got = require('got'); got('https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY', { json: true }).then(response => { console.log(response.body.url); console.log(response.body.explanation); }).catch(error => { console.log(error.response.body); });

如果你想要一个不像Request那样臃肿的轻量级的库,使用Got就对了。

最后的想法

以上并不是全部的解决方案,不过看到了这里,你知道了在Node.js中一些流行的HTTP库中的基本功能是怎样工作的。还有一些库,例如node-fetch将浏览器的获取(fetch)功能移植到后端。在其他语言中也有各种类似的库解决这个问题,比如 Python 和 Ruby 。

5 Ways to Make HTTP Requests in Node.js 原文链接:https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/b358967b4e18633fd7ef3d38a41a6a1b.html