Simple Routing using if else block in nodejs using http module
Node.js is a powerful server-side JavaScript runtime environment that allows you to build scalable web applications. One important aspect of building web applications is managing routing, which involves directing HTTP requests to different endpoints or handlers based on the requested URL.
In this article, we will explore how to implement simple routing using an if else block in a Node.js application using the built-in http module.
Step 1: Create a Node.js server
First, let’s create a basic Node.js server using the http module. Here’s a simple example:
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello, World!
'); }); server.listen(3000, () => { console.log('Server running on port 3000'); });
This code creates a basic HTTP server that listens on port 3000 and responds with “Hello, World!” to any incoming requests.
Step 2: Implement simple routing
Next, let’s implement simple routing using an if else block. We can parse the requested URL from the request object and use it to determine which handler to invoke. Here’s an example:
const http = require('http'); const server = http.createServer((req, res) => { const url = req.url; if (url === '/') { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Welcome to the homepage!
'); } else if (url === '/about') { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('About Us
'); } else { res.writeHead(404, {'Content-Type': 'text/html'}); res.end('Page not found
'); } }); server.listen(3000, () => { console.log('Server running on port 3000'); });
In this code snippet, we check the requested URL using an if else block and serve different content based on the URL. If the URL is ‘/’, we display a welcome message; if it is ‘/about’, we display information about the website; otherwise, we return a 404 error page.
Conclusion
Simple routing is an essential concept in web development, and Node.js makes it easy to implement using the built-in http module. By using an if else block to check the requested URL, you can direct incoming requests to the appropriate handler based on the URL path. As your Node.js application grows, you can further modularize your routing logic using libraries such as Express.js.