Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to initiate HTTP request in Node.js

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to initiate a HTTP request in Node.js. It is very detailed and has certain reference value. Friends who are interested must read it!

Body Node.js HTTPS Module

Node.js comes with a https module in the standard library, so you don't need to introduce any libraries to make requests at all, because node.js itself can do it, and it's more than enough to handle 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);})

The structure is a bit complicated because we need to get an empty array list to store the request block chunk, and then process the data through Buffer and parse it into json format after the request ends.

Axios

I believe that the front-end partners are no stranger to axios, which is a very popular and popular Promise-style request library. It can be used on the browser side and can be used on the client side, and as we all know, it also has very convenient functions such as interceptor, automatic data conversion json and so on.

We can install axios using the following command:

Npm I-S axios

The following is a simple example of how we can get the classification of Nuggets 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 get to request the interface, which can be structured in the form of promise, and the data is automatically parsed into json for you, which is very concise and convenient.

Got

Got claims to be "a humanized and powerful Node.js HTTP request library". Humanization lies in the use of Promise-style API and JOSN processing configuration and other functions, while some capabilities such as HTTP2 support, paged API and RFC cache are not available in most request libraries.

We can install got using the following command:

Npm I-S got@10.7.0

The following is a simple example of how we can get the classification of Nuggets 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 need to configure the request interface {responseType: 'json'}, and then the returned data can be obtained in body, which is also very useful.

Needle

Needle is a relatively simple and compact request library, which can be in the form of Promise or callback function, depending on your habit, and its return value will automatically convert XML to JSON, which is also very convenient.

We can install needle using the following command:

Npm I-S needle

The following is a simple example of how we can get the classification of Nuggets 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 the use of callback functions to show that err and res are returned. If successful, err is null. After success, the body of the returned res contains the requested data. Here is the json format that helps you convert it automatically.

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) {/ /...}); Superagent

The release of the request library superagent is quite early and can be traced back to 2011, but it is a progressive client-side HTTP request library, which supports many advanced HTTP client functions and is still very useful as the Node.js module with the same API.

We can install superagent using the following command:

Npm I-S superagent

The following is a simple example of how we can get the classification of Nuggets 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);})

Today's superagent usage is very similar to axios, but you need to process the data into json format yourself.

Node-fetch

As the name implies, the api of this request library is consistent with window.fetch and is also promise. Recently very popular, but perhaps the biggest problem is that its v2 and v3 version are quite different, v2 maintains the cjs standard, while v3 uses the ejs way, which may cause some trouble after the upgrade, so in order to unify this standard, we use version 2.6.7 as the demonstration version here.

We can install node-fetch using the following command:

Npm I-S node-fetch@2.6.7

The following is a simple example of how we can get the classification of Nuggets 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 exactly the same as window.fetch, without any learning pressure.

Contrast

Next, let's take a look at the trend of downloads of these request libraries in the past year:

Now we can find that in terms of downloads, node-fetch was the most popular and needle the least popular in the past year.

StarsVersionUnpacked SizeCreated Yearsaxios91,6420.26.1398 kB2014got10,73612.0.1244 kB2014needle1,4463.0.0227 kB2012superagent15,9287.1.1581 kB2011node-fetch7,4343.2.3106 kB2015

Here we count some other data from these libraries, and the number of star in axios is far more than that of other libraries.

Conclusion

These request libraries, they have all done the same thing, they can all initiate HTTP requests, which may be written slightly differently, but all roads lead to Rome. Personally, it may also be because you often write on the browser side, so loyal users of axios, whether practicing or developing axios, are the first choice. Of course, node-fetch is also getting more and more attention, the package is also very small, and it is often used when practicing, but api still doesn't feel as convenient 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, mainly built for deno and modern browsers, so don't participate in the discussion for the time being and explore for yourself.

The other is request.js. The reason for not saying is that it has been completely abandoned in 2020. If there is a partner who has used it, he can replace it with other methods in the project.

The above is all the content of the article "how to initiate a HTTP request in Node.js". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report