search
HomeWeb Front-endJS TutorialA brief analysis of 6 ways Node initiates HTTP requests

A brief analysis of 6 ways Node initiates HTTP requests

Dec 09, 2022 pm 08:08 PM
nodejs​nodehttphttp request

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!

A brief analysis of 6 ways Node initiates HTTP requests

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]

Text


Node.js HTTPS Module

##Node.js There is an https module in the standard library, so you don't need to introduce any library to initiate requests, because node.js can do it by itself, 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);
});

The structure is a little complicated, because we need to make an empty array list to store the request data block chunk, and then after the request is completed, the data must be processed through the Buffer and then parsed into json format.

A brief analysis of 6 ways Node initiates HTTP requests

Axios

I believe that front-end friends are no strangers to axios, it is a very popular And the 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

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);
});

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.

A brief analysis of 6 ways Node initiates HTTP requests

Got

got claims to be “a user-friendly and powerful HTTP request for Node.js "Library" is user-friendly because it uses Promise-style APIs and JOSN processing configuration functions. However, some capabilities such as HTTP2 support, paging API and RFC caching are not available in most request libraries.

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);
});

Here we first need to configure the request interface

{responseType: 'json'}, and then the returned data can be obtained in the body, which is also very easy to use.

A brief analysis of 6 ways Node initiates HTTP requests

Needle##needle is a relatively simple and compact request library. Its form can be Promise The method can also be a callback function, which depends on your own habits, and its return value will automatically convert XML and JSON, which is also very convenient.

We can use the following command to install needle:

npm i -S needle

The following 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 the return includes err and res. When successful, err is null. The body of the res returned after success is the data to be requested. Here is how to automatically help you Converted json format.

A brief analysis of 6 ways Node initiates HTTP requestsIf 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) {
    // ...
});

SuperagentThe 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 install superagent using the following command:

npm i -S superagent

下面是我们通过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);
});

现在的superagent用法与axios十分的相似,但是需要去自己把数据处理成json格式。

A brief analysis of 6 ways Node initiates HTTP requests

Node-fetch

顾名思义,这个请求库它的api与window.fetch保持了一致,也是promise式的。最近非常受欢迎,但可能最大的问题是,它的v2与v3版差异比较大,v2保持着cjs标准,而v3则用了ejs的方式,升级后可能造成一些困扰,所以为了统一这个标准我们这里用了2.6.7版作为演示版本。

我们可以使用以下命令安装node-fetch:

npm i -S node-fetch@2.6.7

下面是我们通过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);
});

可以看出它与window.fetch用起来完全一样,没有任何学习压力。

A brief analysis of 6 ways Node initiates HTTP requests

对比


接下来我们看一下关于这几款请求库近一年的下载量趋势图:

A brief analysis of 6 ways Node initiates HTTP requests

现在我们可以发现,就下载量而言,在过去一年中,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它替换成其他的方法。

A brief analysis of 6 ways Node initiates HTTP requests

更多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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool