Setting up an HTTP server in Node.js is essential. There are multiple ways to do so. Axios is a great library, but today I'll focus on Node.js's built-in modules to understand the fundamentals.
HTTP
Hypertext Transfer Protocol (HTTP) is used for communication between a client and a server. HTTP servers handle requests and responses. The methods, or verbs, are GET, POST, PUT, and DELETE. They work with request and response headers and also handle streaming data.
Handling GET Requests
The example code is from the Node.js
repository on GitHub.
I'll break down what each part of the code does to understand the fundamentals.
This is the overall code:
const https = require('https');
const options = {
hostname: 'example.com',
port: 443,
path: '/todos',
method: 'GET',
};
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', error => {
console.error(error);
});
req.end();
const https = require('https');
require('node:https')
is a newer version (Node.js 16+). By explicitly mentioning node
, it can avoid any conflicts.
const options = {
hostname: 'example.com',
port: 443,
path: '/todos',
method: 'GET',
};
The options
object specifies the data for the request. Port 443 is the default for HTTPS; for HTTP, it is 80.
const req = https.request(options, res => {
The res
parameter is a response object that includes the status code, headers, and the actual response body.
res.on('data', d => {
The on
method is an event listener that listens for the data
event emitted when a chunk of the response is received.
process.stdout.write(d);
The process.stdout.write(d);
writes the chunk of data (d)
to the standard output, usually your terminal.
req.on('error', error => {
When an error occurs, the on
method is fired. Without handling an error, Node.js will crash.
req.end();
req.end();
signals that all request data has been sent, completing the request lifecycle. This step is important to ensure the request is processed by the server.
Handling POST Requests
This is the overall code:
const https = require('https');
const data = JSON.stringify({
todo: 'Buy the milk',
});
const options = {
hostname: 'whatever.com',
port: 443,
path: '/todos',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length,
},
};
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
res.on('data', d => {
process.stdout.write(d);
});
});
req.on('error', error => {
console.error(error);
});
req.write(data);
req.end();
const data = JSON.stringify({
todo: 'Buy the milk',
});
We stringify the data to JSON to prepare it for sending.
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length,
},
We specify the header's format as JSON and set the length of the data.
req.write(data);
This code writes the data
to the body of the request, ensuring Buy the milk
is included in the POST request.
GET Request Using createServer
The Node.js documentation shares a simple code snippet using createServer
.
const { createServer } = require('node:http');
const hostname = '127.0.0.1';
const port = 3000;
const server = createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
const { createServer } = require('node:http');
The createServer
method is imported and destructured from the http
module, which is designed to set up an HTTP server.
const server = createServer((req, res) => {
For every incoming HTTP request, the callback function is executed.
req
- The incoming request (e.g., URL, headers, method)
res
- The outgoing response to the client
res.statusCode = 200;
We set the status code to ensure the client receives clear information about the request status.
res.setHeader('Content-Type', 'text/plain');
The setHeader
method is used to define headers for the response.
res.end('Hello World');});
This line sends the body Hello World
and completes the response.
server.listen(port, hostname, () => {
The server starts and listens for incoming connections on the specified port
and hostname
.
By breaking down the built-in modules, I now have a clear understanding and a solid foundation for handling HTTP requests in Node.js. This knowledge will be helpful even when using advanced third-party libraries.
Top comments (0)