Node.js has become a powerful tool for building many kinds of services on the web. It provides variety of built-in modules that can be utilized to meet any developers needs. One of common modules for web developers is HTTP module. This module can be used for handling HTTP request or building a web server.
This following example shows you how to build HTTP and HTTPS server in Node.js. This sample server will accept client request and deliver response with a payload containing what the client was sent.
1. In your project directory, generate self-signed certificates that will be used for configuring HTTPS server. OpenSSL is required for this process.
openssl req -nodes -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365
2. Create a file named server.js.
const http = require('http');
const https = require('https');
const {StringDecoder} = require('string_decoder');
// function that receives request and response parameters from HTTP/HTTPS server object
function serverHandler(req, res) {
// get request headers
const headers = req.headers;
// get request method
const method = req.method.toLowerCase();
// generate URL object based on request detail
const url = new URL(req.url, 'http://' + req.headers.host);
// generate path value without leading and trailing slash
const trimmedPath = url.pathname.replace(/^\/+|\/+$/, '');
// generate query object
const query = Object.fromEntries(url.searchParams.entries());
// get request body
const decoder = new StringDecoder('utf-8');
let bodyStr = '';
req.on('data', function(chunk){
bodyStr += decoder.write(chunk);
});
req.on('end', function(){
bodyStr += decoder.end();
// setup response payload
let responseData = {
method: method,
headers: headers,
path: trimmedPath,
query: query,
body: bodyStr
};
// send the response
res.setHeader('Content-Type', 'application/json');
res.writeHead(200);
res.end(JSON.stringify(responseData));
});
}
// setup server object
const httpServer = http.createServer(serverHandler);
const httpsServer = https.createServer({
key: fs.readFileSync('./key.pem')),
cert: fs.readFileSync('./cert.pem'))
}, serverHandler);
// start listening
httpServer.listen(3000, ()=>{
console.log('HTTP server is running on port 3000');
});
httpsServer.listen(3001, ()=>{
console.log('HTTPS server is running on port 3001');
});
3. Start the server.
node server.js

This tutorial provides a practical introduction to creating HTTP and HTTPS servers in Node.js using its built-in modules. I like how the example demonstrates request handling, reading headers, identifying HTTP methods, and extracting URL paths and query parameters. Understanding these fundamentals is useful for developers who want to build web servers, manage client requests, and learn how secure communication is configured using TLS certificates.
ReplyDeleteFor anyone looking to develop these skills further, a Nodejs Course can help build a stronger foundation in server-side JavaScript, HTTP request and response handling, asynchronous operations, and networking concepts. These skills are valuable when creating APIs and backend services that communicate reliably with web clients.
Once the basics of HTTP and HTTPS are clear, developers can also explore frameworks that simplify server development. An Expressjs Course can help with routing, middleware, and API organization, making it easier to build maintainable web applications on top of Node.js RESTful API Course.
ReplyDelete