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
Comments
Post a Comment