The code demonstrates how to build a basic Node.js server that can handle routing for different paths. You can modify the actions object to add more routes and customize the content for each route. The server listens for incoming requests, routes them to the appropriate handlers, and responds with HTML content.
const {createServer} = require('http');
const server = createServer();
const PORT = 9090;
// start server on provided port
server.listen(PORT, () => {
console.log(`Server started and running on http://localhost:${PORT}.`)
});
// listen for client connections
server.on('connection', (client) => {
const {address} = client.address();
console.log(`Client with address ${address} connected to the server.`);
});
// handles a http request
server.on('request', function (request, response) {
routes(request, response);
});
// handle route requests
const routes = (request, response) => {
// for all routes; for individual routes, move to the respective route case
response.setHeader('Content-Type', 'text/html');
// route actions as per request URL
const actions = {
'/' : () => {
response.write('<h1>Hello, Node.js!</h1>');
},
'/about' : () => {
response.write('<h1>About Node.js</h1>');
},
'/contact' : () => {
response.write('<h1>Contact</h1>');
},
'/faq' : () => {
response.write('<h1>FAQ</h1>');
},
'*' : () => {
response.write('<h1>Not Found | 404</h1>');
}
};
// calls the appropriate function based on the requested URL
(actions[request.url] || actions['*'])();
response.end();
};
In conclusion, this tutorial provided a solid foundation for building a basic Node.js server with routing capabilities. You learned how to handle client connections, route requests to different paths, and send HTML responses.
If you found this code informative and would love to see more, don’t forget to subscribe to our newsletter! 😊