How to make an HTTP request in Node.js?
There are three common ways to initiate HTTP requests in Node.js: using built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or sending POST requests through .write(); 2. axios is a third-party library based on Promise. It has concise syntax and powerful functions. It supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3. node-fetch provides a style similar to browser fetch, based on Promise and simple syntax. It requires introducing modules and calling .json() or .text() to parse the response content. The choice depends on project requirements and development preferences.

Initiating HTTP requests in Node.js is the basis of many backend tasks, such as calling external APIs, obtaining remote data, etc. The most common way is to use built-in http or https modules, or simplify operations with third-party libraries such as axios and node-fetch .

Use built-in module: http/https
Node.js comes with http and https modules, which can be used to send original HTTP requests. This method does not require additional installation dependencies and is suitable for basic scenarios.

Take https.get() as an example:
const https = require('https');
https.get('https://api.example.com/data', (res) => {
let data = '';
res.on('data', (chunk) => {
data = chunk;
});
res.on('end', () => {
console.log(JSON.parse(data));
});
}).on('error', (err) => {
console.error(err);
});- This method requires manual splicing of response data (via
'data'event) - Pay attention to handling errors (listen to
errorevents) - If it is a POST request, you also need to set headers and use
.write()to send data
Use axios to initiate a request
axios is a very popular third-party HTTP client. It is based on Promise and is simpler to use and more powerful.

First install:
npm install axisos
Then use:
const axios = require('axios'); axios.get('https://api.example.com/data') .then(response => console.log(response.data)) .catch(error => console.error(error));
Advantages include:
- Support async/await writing
- Automatically convert JSON data
- Support interceptor, cancel request and other functions
If it is a POST request:
axios.post('https://api.example.com/submit', {
name: 'test',
})
.then(response => console.log(response.data))
.catch(error => console.error(error));Use node-fetch to simplify writing
If you want to use a syntax style similar to fetch in your browser, you can use node-fetch . It is also based on Promise and has a concise syntax.
Install first:
npm install node-fetch
Use again:
const fetch = require('node-fetch'); fetch('https://api.example.com/data') .then(res => res.json()) .then(json => console.log(json)) .catch(err => console.error(err));
Notice:
- The body returned by default is in a stream form, and needs to be converted using
.json()or.text() - Not globally available like a browser, modules are required
Basically, it depends on your project needs and preferences. If you pursue simplicity and convenience, it is recommended to use axios ; if you want to keep the code style unified, you can use node-fetch ; if you don’t want to pack it, you can also use built-in modules.
The above is the detailed content of How to make an HTTP request in Node.js?. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Clothoff.io
AI clothes remover
Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1793
16
1737
56
1588
29
267
587
Solution: Socket Error when handling HTTP requests
Feb 25, 2024 pm 09:24 PM
http request error: Solution to SocketError When making network requests, we often encounter various errors. One of the common problems is SocketError. This error is thrown when our application cannot establish a connection with the server. In this article, we will discuss some common causes and solutions of SocketError. First, we need to understand what Socket is. Socket is a communication protocol that allows applications to
How to send email using PHP HTTP request
May 21, 2023 pm 07:10 PM
PHP is a widely used programming language, and one of its common applications is sending emails. In this article, we will discuss how to send emails using HTTP requests. We will introduce this topic from the following aspects: What is an HTTP request? Basic principles of sending emails using PHP. Sending HTTP requests. Sample code for sending emails. What is an HTTP request? An HTTP request refers to a request sent to a web server to obtain a web resource. . HTTP is a protocol used in web browsers and we
From start to finish: How to use php extension cURL to make HTTP requests
Jul 29, 2023 pm 05:07 PM
From start to finish: How to use php extension cURL for HTTP requests Introduction: In web development, it is often necessary to communicate with third-party APIs or other remote servers. Using cURL to make HTTP requests is a common and powerful way. This article will introduce how to use PHP to extend cURL to perform HTTP requests, and provide some practical code examples. 1. Preparation First, make sure that php has the cURL extension installed. You can execute php-m|grepcurl on the command line to check
Cause analysis: HTTP request error 504 gateway timeout
Feb 19, 2024 pm 05:12 PM
Brief introduction to the reason for the http request error: 504GatewayTimeout: During network communication, the client interacts with the server by sending HTTP requests. However, sometimes we may encounter some error messages during the process of sending the request. One of them is the 504GatewayTimeout error. This article will explore the causes and solutions to this error. What is the 504GatewayTimeout error? GatewayTimeo
How to solve the problem of HTTP request connection refused in Java development
Jun 29, 2023 pm 02:29 PM
How to solve the problem of HTTP request connection being refused in Java development. In Java development, we often encounter the problem of HTTP request connection being refused. This problem may occur because the server side restricts access rights, or the network firewall blocks access to HTTP requests. Fixing this problem requires some adjustments to your code and environment. This article will introduce several common solutions. Check the network connection and server status. First, confirm that your network connection is normal. You can try to access other websites or services to see
How Nginx implements retry configuration of HTTP requests
Nov 08, 2023 pm 04:47 PM
How Nginx implements HTTP request retry configuration requires specific code examples. Nginx is a very popular open source reverse proxy server. It has powerful functions and flexible configuration options and can be used to implement HTTP request retry configuration. In network communication, sometimes the HTTP request we initiate may fail due to various reasons, such as network delay, server load, etc. In order to improve the reliability and stability of the application, we may need to retry when the request fails. The following will introduce how to use Ng
How to use Nginx for compression and decompression of HTTP requests
Aug 02, 2023 am 10:09 AM
How to use Nginx to compress and decompress HTTP requests Nginx is a high-performance web server and reverse proxy server that is powerful and flexible. When processing HTTP requests, you can use the gzip and gunzip modules provided by Nginx to compress and decompress the requests to reduce the amount of data transmission and improve the request response speed. This article will introduce the specific steps of how to use Nginx to compress and decompress HTTP requests, and provide corresponding code examples. Configure gzip module
Set query parameters for HTTP requests using Golang
Jun 02, 2024 pm 03:27 PM
To set query parameters for HTTP requests in Go, you can use the http.Request.URL.Query().Set() method, which accepts query parameter names and values as parameters. Specific steps include: Create a new HTTP request. Use the Query().Set() method to set query parameters. Encode the request. Execute the request. Get the value of a query parameter (optional). Remove query parameters (optional).


