How to initiate an HTTP request in Node? This article will explore with you the 6 different methods of Node to initiate HTTP requests. I hope it will be helpful to you!
This article introduces 6 different methods of initiating HTTP requests in nodejs. Here we will dig through The request of Jin Community’s section classification interface
is used as a demonstration to complete the use of each different method. Of course, in order to print out the obtained data more clearly, we need to install the chalk library
in advance. Add color to the printed data, okay, we are about to start~ [Related tutorial recommendations: nodejs video tutorial, Programming teaching]
const chalk = require("chalk") const https = require('https') https.get('https://api.juejin.cn/tag_api/v1/query_category_briefs', res => { let list = []; res.on('data', chunk => { list.push(chunk); }); res.on('end', () => { const { data } = JSON.parse(Buffer.concat(list).toString()); data.forEach(item => { console.log(`${chalk.yellow.bold(item.rank)}.${chalk.green(item.category_name)}`); }) }); }).on('error', err => { console.log('Error: ', err.message); });
We can use the following command to install axios:
npm i -S axios
The following is a simple example of how we obtain the Nuggets plate classification through axios:
const chalk = require("chalk") const axios = require('axios'); axios.get('https://api.juejin.cn/tag_api/v1/query_category_briefs') .then(res => { const { data } = res.data data.forEach(item => { console.log(`${chalk.yellow.bold(item.rank)}.${chalk.green(item.category_name)}`); }) }) .catch(err => { console.log('Error: ', err.message); });
We can use the following command to install got:
npm i -S got@10.7.0
The following is a simple example of how we get the Nuggets plate classification through got:
const chalk = require("chalk") const got = require('got'); got.get('https://api.juejin.cn/tag_api/v1/query_category_briefs', { responseType: 'json' }) .then(res => { const { data } = res.body data.forEach(item => { console.log(`${chalk.yellow.bold(item.rank)}.${chalk.green(item.category_name)}`); }) }) .catch(err => { console.log('Error: ', err.message); });
{responseType: 'json'}, and then the returned data can be obtained in the body, which is also very easy to use.
npm i -S needle
const chalk = require("chalk")
const needle = require('needle');
needle.get('https://api.juejin.cn/tag_api/v1/query_category_briefs', (err, res) => {
if (err) return console.log('Error: ', err.message);
const { data } = res.body
data.forEach(item => {
console.log(`${chalk.yellow.bold(item.rank)}.${chalk.green(item.category_name)}`);
})
})
If you want to use Promise, you can write like this:
needle('get', 'https://api.juejin.cn/tag_api/v1/query_category_briefs') .then(function(res) { // ... }) .catch(function(err) { // ... });
下面是我们通过superagent获取掘金板块分类简单示例: 现在的superagent用法与axios十分的相似,但是需要去自己把数据处理成json格式。 顾名思义,这个请求库它的api与window.fetch保持了一致,也是promise式的。最近非常受欢迎,但可能最大的问题是,它的v2与v3版差异比较大,v2保持着cjs标准,而v3则用了ejs的方式,升级后可能造成一些困扰,所以为了统一这个标准我们这里用了2.6.7版作为演示版本。 我们可以使用以下命令安装node-fetch: 下面是我们通过node-fetch获取掘金板块分类简单示例:npm i -S superagent
const chalk = require("chalk")
const superagent = require('superagent');
superagent.get('https://api.juejin.cn/tag_api/v1/query_category_briefs')
.then(res => {
const { data } = JSON.parse(res.text)
data.forEach(item => {
console.log(`${chalk.yellow.bold(item.rank)}.${chalk.green(item.category_name)}`);
})
})
.catch(err => {
console.log('Error: ', err.message);
});
Node-fetch
npm i -S node-fetch@2.6.7
const chalk = require("chalk")
const fetch = require("node-fetch")
fetch('https://api.juejin.cn/tag_api/v1/query_category_briefs', {
method: 'GET'
})
.then(async res => {
let { data } = await res.json()
data.forEach(item => {
console.log(`${chalk.yellow.bold(item.rank)}.${chalk.green(item.category_name)}`);
})
})
.catch(err => {
console.log('Error: ', err.message);
});
可以看出它与window.fetch用起来完全一样,没有任何学习压力。
接下来我们看一下关于这几款请求库近一年的下载量趋势图:
现在我们可以发现,就下载量而言,在过去一年中,node-fetch 最受欢迎,needle 最不受欢迎。
Stars | Version | Unpacked Size | Created Years | |
---|---|---|---|---|
axios | 91,642 | 0.26.1 | 398 kB | 2014 |
got | 10,736 | 12.0.1 | 244 kB | 2014 |
needle | 1,446 | 3.0.0 | 227 kB | 2012 |
superagent | 15,928 | 7.1.1 | 581 kB | 2011 |
node-fetch | 7,434 | 3.2.3 | 106 kB | 2015 |
这里我们又统计了这几个库的其他一些数据,axios的star数量可谓一骑绝尘,远远超过其他几个库。
这些请求库,他们都做了同一件事都可以发起HTTP请求,或许写法会有些许不同,但都是条条大路通罗马。就个人而言,也可能是经常写浏览器端的缘故,所以是axios的忠实用户,不管是练习还是开发axios都是首选,当然node-fetch也越来越收到关注,包也十分的小,练习的时候也会经常用到,但api使用起来感觉还是没有axios那般方便。
其实还有两个出名的HTTP请求库本文没有提到:
一个是ky.js,它是一个非常小巧且强大的fetch式的请求库,主要为deno和现代浏览器所打造,所以暂时不参与其中的讨论,感兴趣的同学自己探索。
另一个就是request.js,没有说的原因是它在2020年的时候就已经被完全弃用了,如果有使用过的小伙伴可以在把项目里的request它替换成其他的方法。
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of A brief analysis of 6 ways Node initiates HTTP requests. For more information, please follow other related articles on the PHP Chinese website!