Basic Routing in Node.js
Routing in Node.js allows you to handle different URL paths and send appropriate responses. This guide will walk you through creating a simple HTTP server with basic routing.
Setting Up a Basic Server
First, create a simple HTTP server using the http module:
import { createServer } from 'http';
const server = createServer((req, res) => {// Basic routing logic will go here});
server.listen(3000, () => {console.log('Server is running on http://localhost:3000');});Handling Different URL Paths
You can handle different URL paths by checking the req.url property:
const server = createServer((req, res) => {if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Welcome to the homepage!');} else if (req.url === '/about') { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('This is the about page.');} else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Page not found!');}});Responding with Different Data
const server = createServer((req, res) => {if (req.url === '/json') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Hello, JSON!' }));}});In the above example, the server sends different responses based on the URL path. You can easily extend this to serve HTML, JSON, or other content types.