HTTP Request
To send HTTP requests from Node.js, you can use the standard modules 'http' and 'https', or the global function 'fetch' available from Node.js 18 onwards. These are used in a variety of situations such as communicating with external APIs and web scraping.
Comparison of Main Approaches
| Approach | Module / Function | Description |
|---|---|---|
http.get() | http / https | A shorthand method of the standard module for sending GET requests concisely. |
http.request() | http / https | A general-purpose method of the standard module that lets you specify detailed options such as method, headers, and body. |
fetch() | Global (Node.js 18+) | A Promise-based function that sends HTTP requests using the same API as in the browser. |
http.get() — Sending a GET Request
For HTTPS URLs, use require('https'). The callback receives a response object (res).
http_get.js
var https = require('https');
// Send a GET request with https.get()
// Example: access the profile API for Kiryu Kazuma
https.get('https://api.example.com/characters/kiryu', function(res) {
var body = '';
// Receive data chunk by chunk
res.on('data', function(chunk) {
body += chunk;
});
// Reception complete
res.on('end', function() {
console.log('Status code:', res.statusCode);
console.log('Response:', body);
});
}).on('error', function(err) {
console.error('Error:', err.message);
});
node http_get.js
Status code: 200
Response: {"name":"Kiryu Kazuma","title":"Like a Dragon","age":37}
http.request() — Sending a POST Request
http.request() lets you specify detailed settings such as method, headers, and hostname using an options object. The request body is sent with req.write().
http_post.js
var https = require('https');
// JSON data to send (message from Majima Goro)
var data = JSON.stringify({
from: 'majima',
message: 'Welcome to the yakuza world, bro'
});
// Request option settings
var options = {
hostname: 'api.example.com',
port: 443,
path: '/messages',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
};
var req = https.request(options, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
// Parse the response JSON
var result = JSON.parse(body);
console.log('Sent:', result.status);
});
});
// Error handling
req.on('error', function(err) {
console.error('Request error:', err.message);
});
// Write the body and complete the request
req.write(data);
req.end();
node http_post.js Sent: ok
fetch() — Sending Requests with Promises (Node.js 18+)
From Node.js 18 onwards, the same fetch() as in the browser is available globally. Combining it with async/await produces readable code.
fetch_get.js
// fetch() is available globally from Node.js 18 onwards
// Retrieve JSON with a GET request
async function getCharacter(id) {
try {
// Send a request with the ID in the URL
var res = await fetch('https://api.example.com/characters/' + id);
// Treat any HTTP status outside the 2xx range as an error
if (!res.ok) {
throw new Error('HTTP error: ' + res.status);
}
// Parse the response as JSON
var data = await res.json();
console.log('Name:', data.name);
console.log('Affiliation:', data.team);
} catch (err) {
console.error('Fetch failed:', err.message);
}
}
// Retrieve character information for Kasuga Ichiban
getCharacter('kasuga');
node fetch_get.js Name: Kasuga Ichiban Affiliation: Like a Dragon
fetch() — Setting Headers and a POST Body
fetch_post.js
// Send JSON with a POST request
async function postMessage(payload) {
var res = await fetch('https://api.example.com/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Set the authentication token in the header
'Authorization': 'Bearer nishikiyama_token_abc123'
},
// Convert the object to a JSON string and send it
body: JSON.stringify(payload)
});
var result = await res.json();
console.log('Response:', result);
}
postMessage({
sender: 'Nishikiyama Akira',
message: 'Kiryu-san, I have a favour to ask'
});
node fetch_post.js
Response: { status: 'sent', id: 'msg_0042' }
Sample Code — Fetching and Displaying JSON from an API
A sample that fetches information for multiple characters at once and formats the output. Promise.all() sends the requests in parallel.
fetch_all.js
// ID list of Like a Dragon characters
var characters = ['kiryu', 'majima', 'kasuga', 'nishikiyama', 'sawamura'];
// Fetch information for all characters in parallel
async function fetchAll() {
// Collect fetch Promises into an array with map()
var promises = characters.map(function(id) {
return fetch('https://api.example.com/characters/' + id)
.then(function(res) { return res.json(); });
});
// Wait until all requests are complete
var results = await Promise.all(promises);
results.forEach(function(c) {
// Format and output name and age
console.log(c.name + ' (age ' + c.age + ')');
});
}
fetchAll();
node fetch_all.js Kiryu Kazuma (age 37) Majima Goro (age 38) Kasuga Ichiban (age 42) Nishikiyama Akira (age 36) Sawamura Haruka (age 21)
Overview
There are three main ways to send HTTP requests in Node.js. The standard http.get() is well suited for sending GET requests conveniently, while http.request() is used when you need fine-grained control over the method and headers. From Node.js 18 onwards, fetch() became available globally, allowing you to write Promise-based asynchronous communication with the same API as in the browser. When you want to implement HTTP communication using only standard features without introducing external packages such as axios, you can choose among these options depending on the situation.
For HTTPS URLs, use require('https'). Sending a request to an HTTPS URL with require('http') will not return data.
Common Mistakes
Using require('http') to access an HTTPS URL and getting no data back
The require('http') module is dedicated to the HTTP protocol (http://). Using it against an https:// URL causes a protocol mismatch and data cannot be received. Always use require('https') for HTTPS URLs.
NG example (using the http module for an HTTPS URL):
var http = require('http'); // using the http module
// Trying to access an HTTPS URL, but no data will be returned
http.get('https://api.example.com/characters/kiryu', function(res) {
var body = '';
res.on('data', function(chunk) { body += chunk; });
res.on('end', function() { console.log(body); });
}).on('error', function(err) {
console.error('Error:', err.message);
});
OK example (use the https module for HTTPS URLs):
var https = require('https'); // using the https module
https.get('https://api.example.com/characters/kiryu', function(res) {
var body = '';
res.on('data', function(chunk) { body += chunk; });
res.on('end', function() { console.log(body); });
}).on('error', function(err) {
console.error('Error:', err.message);
});
Forgetting to check res.ok in fetch and treating a 404 as a successful response
fetch() does not reject its Promise when an HTTP error status such as 404 or 500 is returned. Only network errors cause a rejection. Therefore, if you do not check res.ok (which is true when the status code is 200–299), you will end up processing an error response as normal data.
NG example (not checking res.ok):
async function getCharacter(id) {
var res = await fetch('https://api.example.com/characters/' + id);
// res.ok is not checked — execution continues even on a 404
var data = await res.json();
console.log('Name:', data.name);
}
getCharacter('unknown_id');
OK example (check res.ok and throw an error):
async function getCharacter(id) {
var res = await fetch('https://api.example.com/characters/' + id);
// Treat HTTP error statuses explicitly as errors
if (!res.ok) {
throw new Error('HTTP error: ' + res.status);
}
var data = await res.json();
console.log('Name:', data.name);
}
getCharacter('unknown_id');
If you find any errors or copyright issues, please contact us.