This article introduces 6 different methods of initiating HTTP requests in nodejs. Here we will complete the use of each different method by requesting掘金社区的板块分类接口
as a demonstration. Of course, in order to print out the obtained data more clearly , we need to install chalk库
in advance to add color to the printed data. Okay, we are about to start~
Node.js comes with the https module in the standard library, so you don’t need it at all Introduce any library to initiate requests, because node.js itself can complete it, and it is more than enough to handle some simple data requests.
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); });
It is a bit complicated in structure, because we need to make an empty array list to store the request data chunk, and then after the request is completed, we need to process the data through Buffer and then parse it into json format.
believes that front-end friends are familiar with axios. It is a very popular and popular Promise request library. It can be used on both the browser and the client, and as we all know, it also has very convenient functions such as interceptors and automatic data conversion to json.
We can use the following command to install axios:
npm i -S axios
Here is a simple example of how we get the Nuggets section 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); });
Here axios directly uses the get request to request the interface. The structure can also be in the form of promise, and the data is automatically parsed into json for you, which can be said to be very simple and convenient.
got claims to be "a user-friendly and powerful Node.js HTTP request library". The user-friendliness lies in its use of Promise-style API and JOSN processing configuration, and some such as HTTP2 support, paging API and RFC's caching and other capabilities are not available in most request libraries.
We can use the following command to install got:
npm i -S [email protected]
Here is a simple example of how we get the Nuggets section 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); });
Here we first need to configure the request interface with {responseType: 'json'}
, and then the returned data can be obtained in the body, which is also very easy to use.
needle is a relatively simple and compact request library. It can be in the form of Promise or callback function. You can choose it according to your own habits. Moreover, its return value will automatically convert XML and JSON, which is also very useful. of convenience.
We can use the following command to install needle:
npm i -S needle
Here is a simple example of how we obtain the Nuggets section classification through 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)}`); }) })
Here we demonstrate using a callback function. It can be seen that there are err and res returned. When successful, err is null. The body of the res returned after success is the requested data. Here is an automatic conversion for you. Good json format.
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) { // ... });
request library superagent was released quite early, dating back to 2011, but it is a progressive client HTTP request library that supports many advanced HTTP client functions with the Node.js module with the same API. Still very useful.
We can use the following command to install superagent:
npm i -S superagent
Here is a simple example of how we get the Nuggets section classification through 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); });
The current superagent usage is very similar to axios, but you need to process the data into json format yourself.
As the name suggests,is a request library whose API is consistent with window.fetch and is also promise-based. It has been very popular recently, but perhaps the biggest problem is that there is a big difference between its v2 and v3 versions. v2 maintains the cjs standard, while v3 uses the ejs method, which may cause some trouble after the upgrade, so in order to unify this standard we Version 2.6.7 is used here as a demonstration version.
We can use the following command to install node-fetch:
npm i -S [email protected]
Here is a simple example of how we get the Nuggets section classification through node-fetch:
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); });
It can be seen that it is used exactly the same as window.fetch, without any learning pressure.
, let’s take a look at the download trend chart of these request libraries in the past year:
Now we can see that node-fetch has been the most popular and needlele the least popular in terms of downloads over the past year.
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 | , 4343.2.3 | 106 kB | 2015Here |
Us After counting some other data of these libraries, the number of stars of axios can be said to be unparalleled, far exceeding that of several other libraries.
These request libraries, they all do the same thing and can initiate HTTP requests. Maybe the writing methods are slightly different, but all roads lead to Rome. Personally speaking, it may be because I often write on the browser side, so I am a loyal user of axios. Whether it is practicing or developing axios, it is my first choice. Of course, node-fetch is also receiving more and more attention, and the package is also very small. It is often used during practice, but the API is still not as convenient to use as axios.
In fact, there are two famous HTTP request libraries not mentioned in this article:
one is ky.js, which is a very small and powerful fetch-style request library. It is mainly built for deno and modern browsers, so I will not participate in it for the time being. Discussion, interested students can explore on their own.
The other is request.js. The reason why it is not mentioned is that it has been completely deprecated in 2020. If you have used it, you can replace the request in the project with other methods.
This article is reproduced from: https://juejin.cn/post/7074749427637813284
Author: jsmask