This article describes how to send an HTTP request using http, the standard library of Node.js, with methods and headers specified. We will use Express to create a server that sends back information about HTTP requests received to confirm that it works. The related resources of this article are shown below.
The workflow is as follows.
- Coding preparation
- Coding
- Operation check
Run the following commands in the terminal to prepare for coding.
mkdir nodejs-http-request
cd nodejs-http-request
npm init -y
npm install --save express
touch server.js client.js
Open server.js in the editor and enter the following content.
Open client.js in the editor and enter the following content.
The key points are shown below.
- Create an HTTP request using the http.request function.
- Register Promise's resolve for HTTP request's response event.
- Register Promise's reject for HTTP request's error event.
- Write the HTTP request body using the write method of HTTP request.
- Complete HTTP request using the end method of HTTP request.
- Register event handlers for the three events: data, end, and error of the HTTP response. For the data event, add the chunk of the HTTP response body fragment to the end of the chunks list.
- For the end event, call Promise's resolve function with the chunks list.
- For the error event, call Promise's reject function.
- Call Buffer.concat function to combine the HTTP response body fragments.
Run the following command in a terminal to start the server.
node server.js
Start a new terminal and then run the following command to send an HTTP request.
node client.js
Verify that the execution result matches the following.
{
"method": "POST",
"url": "/pathname?query=1",
"query": {
"query": "1"
},
"headers": {
"content-type": "text/plain",
"content-length": "7",
"x-header": "X-Header",
"host": "localhost:3000",
"connection": "close"
},
"body": "content"
}
When sending HTTP requests in Node.js, I use node-fetch, which is easy to use because a process that would take about 40 lines with the standard library can be completed in a few lines with fetch. There are many situations where we want to send HTTP requests from Node.js, such as when obtaining OAuth 2.0 access tokens or when conducting API tests. I don't know much about this because I've never done it before, but do people also use HTTP requests for communication between services in a microservice architecture? (And I don't know much about it, but do they use gRPC or something like that?)
I can't imagine what the situation is like, but I hope this article is useful for those who want to send HTTP requests in Node.js without using npm packages such as node-fetch. Thank you for reading!