Q1. How do you implement routing in a raw Node.js HTTP server?
Parse req.method and req.url to determine the route.
Example:
This forms the basis of routing.
Example:
const { method, url } = req; if (method === 'GET' && url === '/users') { // handle get users } else if (method === 'POST' && url === '/users') { // handle create user } else { // 404 }This forms the basis of routing.
Q2. How do you handle dynamic routes like /users/:id?
Parse the URL and extract parameters using regular expressions or string manipulation.
Example:
More sophisticated routing would use URL pattern matching.
Example:
const urlParts = req.url.split('/'); if (req.url.startsWith('/users/') && urlParts.length === 3) { const id = urlParts[2]; // handle user with id }More sophisticated routing would use URL pattern matching.
Q3. How do you parse query parameters in a route?
Use the url module:
Then use pathname for routing and query for parameters like ?page=2.
const url = require('url'); const parsedUrl = url.parse(req.url, true); const query = parsedUrl.query; // object with query params const pathname = parsedUrl.pathname;Then use pathname for routing and query for parameters like ?page=2.
Q4. How do you handle different HTTP methods for the same route?
Check req.method inside your route handler.
Example:
This implements RESTful routing.
Example:
if (req.url === '/api/data') { switch(req.method) { case 'GET': // handle GET; case 'POST': // handle POST; default: res.statusCode = 405; res.end('Method Not Allowed'); } }This implements RESTful routing.
Q5. How do you create a simple router function?
Create a routes object:
Then in the server, look up handler based on `${req.method} ${req.url}`. This pattern is the foundation of many routing libraries.
const routes = { 'GET /': homeHandler, 'GET /users': usersHandler, 'POST /users': createUserHandler };Then in the server, look up handler based on `${req.method} ${req.url}`. This pattern is the foundation of many routing libraries.
