This article is participating in node.js advanced technology essay, click to see more details

introduce

This will introduce 6 kinds of different methods in the node. Js to initiate an HTTP request, here we will through the plate of the nuggets community classification the request as a demonstration of the interface to complete the use of each method, of course, in order to more clearly to print out the resulting data, we want to advance the installation chalk library to add color to the print data, Okay, we’re about to get started

The body of the

Node.js HTTPS Module

Node.js comes with an HTTPS module in the standard library, so you don’t need to import any libraries to initiate requests at all, because Node.js can handle simple data requests on its own.

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);
});
Copy the code

Structurally, it’s a little complicated because we have to make an empty array list to hold chunks of the request data, and then we have to process the data through Buffer after the request and parse it into JSON format.

Axios

Those of you who believe in the front end are no strangers to Axios, a very popular and popular promise-like request library. It can be used on the browser side, it can be used on the client side, and it is known to have interceptors, automatic data conversion JSON and other very convenient features.

We can install Axios using the following command:

npm i -S axios
Copy the code

Here’s a simple example of how we got the nuggets by 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);
});
Copy the code

Here, AXIos directly uses get to request the interface, which can be structured in the form of promise. The data will be automatically parsed into JSON, which is very simple and convenient.

Got

Got claims to be “a user-friendly and powerful Node.js HTTP request library.” It’s user-friendly because it uses Promise apis and JOSN processing configuration, but some features such as HTTP2 support, paging apis, and RFC caching are not available in most request libraries.

We can install the GOT using the following command:

NPM I - S [email protected]Copy the code

The following is a simple example of the classification of nuggets by 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);
});
Copy the code

{responseType: ‘json’}, and then return the data in the body, which is very useful.

Needle

Needle is a relatively simple and compact request library, its form can be the way of Promise or callback function, depending on their own habits, and its return value will automatically convert XML and JSON, is also very convenient.

We can install the needle using the following command:

npm i -S needle
Copy the code

Here is a simple example of how we get the gold mining plate 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)}`); })})Copy the code

Err and RES are returned. On success, err is null. The body of the RES returned after success is the requested data.

If you want to use Promise, you can write:

needle('get'.'https://api.juejin.cn/tag_api/v1/query_category_briefs')
.then(function(res) {
    // ...
})
.catch(function(err) {
    // ...
});
Copy the code

Superagent

The superAgent request library was released in 2011, but it is a progressive client HTTP request library. It supports many advanced HTTP client functions with the same API as the Node.js module, and is still very useful.

We can use the following command to install the superagent:

npm i -S superagent
Copy the code

The following is a simple example of obtaining gold mining plate classification by 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);
});
Copy the code

The current use of superAgent is very similar to Axios, but requires that the data be processed into JSON format itself.

Node-fetch

As the name suggests, this request library has the same API as Window.fetch and is also promise-like. Recently, it is very popular, but perhaps the biggest problem is that its V2 version is quite different from V3 version, V2 maintains CJS standard, while V3 uses EJS method, which may cause some confusion after upgrading, so in order to unify this standard, we use 2.6.7 version as the demo version.

We can install node-fetch using the following command:

NPM I - S [email protected]Copy the code

Here is a simple example of how we can get the gold mining plate 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);
});
Copy the code

You can see that it works exactly the same as window.fetch without any learning pressure.

contrast

Let’s take a look at the download trends for each request library over the past year:

Now we can see that in terms of downloads over the past year, Node-Fetch was the most popular and Needle was the least popular.

Stars Version Unpacked Size Created Years
axios 91642 0.26.1 398 kB 2014
got 10736 12.0.1 244 kB 2014
needle 1446 3.0.0 227 kB 2012
superagent 15928 7.1.1 581 kB 2011
node-fetch 7434 3.2.3 106 kB 2015

Here we look at some of the other numbers for these libraries, and axios’s star count is by far the highest among the other libraries.

conclusion

These libraries of requests, they all do the same thing and they can all make HTTP requests, maybe written a little bit differently, but they all lead to Rome. Personally, it may be because I often write on the browser side, so I am a loyal user of Axios. I prefer to practice and develop AXIos. Of course, Node-Fetch is getting more and more attention, and the package is very small, and I often use it in practice.

There are two well-known HTTP request libraries that are not covered in this article:

One is Ky.js, which is a very small and powerful FETCH type request library, mainly created by deno and modern browsers, so I will not participate in the discussion for the moment, and students who are interested in it will explore by themselves.

The other is Request.js, which was completely deprecated in 2020. If you have used it, you can replace it with another method in your project.