Routing requests manually means deciding what to do based on the web address a user visits. It helps your server send the right response for each request.
Routing requests manually in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/') { // handle root path } else if (req.url === '/about') { // handle about page } else { // handle 404 not found } }); server.listen(3000);
Use req.url to check the requested path.
Use res.writeHead() and res.end() to send responses.
Examples
Node.js
if (req.url === '/') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Home page'); }
Node.js
if (req.url === '/about') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('About us'); }
Node.js
res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('Page not found');
Sample Program
This server listens on port 3000. It sends a welcome message for the root URL, contact info for '/contact', and a 404 message for other URLs.
Node.js
const http = require('http'); const server = http.createServer((req, res) => { if (req.url === '/') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Welcome to the Home page!'); } else if (req.url === '/contact') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Contact us at contact@example.com'); } else { res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('404: Page not found'); } }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
Important Notes
Check req.method if you want to handle GET, POST, or other HTTP methods differently.
Manual routing is simple but can get hard to manage for many routes; frameworks help with this.
Summary
Manual routing uses req.url to decide how to respond.
Use res.writeHead() and res.end() to send responses.
This method is good for learning or small servers without extra tools.
Practice
1. What is the main purpose of checking
req.url in a Node.js server without frameworks?easy
Solution
Step 1: Understand the role of
req.urlreq.urlcontains the path requested by the client, like '/home' or '/about'.Step 2: Purpose of checking
By checkingreq.urlreq.url, the server can decide which content or response to send back.Final Answer:
To decide how to respond to different request paths -> Option AQuick Check:
Routing = Check req.url [OK]
Hint: Check req.url to route requests manually [OK]
Common Mistakes:
- Thinking req.url parses request body
- Confusing req.url with database connection
- Assuming req.url handles authentication
2. Which of the following is the correct way to send a plain text response with status 200 in a manual Node.js server?
easy
Solution
Step 1: Identify correct methods for manual response
In manual Node.js servers,res.writeHead()sets status and headers,res.end()sends the response body.Step 2: Check each option
res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello'); useswriteHeadandendcorrectly. The second and third options use Express methods, not native Node.js. res.write(200, 'Hello'); is invalid syntax.Final Answer:
res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello'); -> Option BQuick Check:
Manual response = writeHead + end [OK]
Hint: Use writeHead and end to send manual responses [OK]
Common Mistakes:
- Using Express methods in plain Node.js
- Calling res.write without headers
- Incorrect method names like res.sendStatus
3. What will the following Node.js server code output when a client requests
/hello?
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/hello') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World');
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000);medium
Solution
Step 1: Check the request URL condition
The code checks ifreq.url === '/hello'. If true, it sends 'Hello World' with status 200.Step 2: Determine output for '/hello'
Since the request is '/hello', the first branch runs, sending 'Hello World'.Final Answer:
Hello World -> Option CQuick Check:
req.url '/hello' = 'Hello World' [OK]
Hint: Match req.url exactly to send correct response [OK]
Common Mistakes:
- Assuming default response is 'Hello World'
- Confusing 404 and 200 responses
- Expecting server error without syntax issues
4. Identify the error in this manual routing code snippet:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url = '/test') {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Test page');
} else {
res.writeHead(404);
res.end('Page not found');
}
});
server.listen(3000);medium
Solution
Step 1: Check the if condition syntax
The condition usesreq.url = '/test', which assigns instead of compares. This always evaluates to true.Step 2: Identify correct comparison operator
It should bereq.url === '/test'to compare values properly.Final Answer:
Using assignment (=) instead of comparison (===) in if condition -> Option DQuick Check:
Use === for comparison, not = [OK]
Hint: Use === for comparison, not = [OK]
Common Mistakes:
- Confusing assignment and comparison operators
- Forgetting to call res.end()
- Incorrect header object syntax
5. You want to manually route requests to serve JSON data at
/data and plain text at /info. Which code snippet correctly implements this?hard
Solution
Step 1: Check content types for each route
For/data, JSON content type 'application/json' is correct. For/info, plain text 'text/plain' is correct.Step 2: Verify response body and headers
if (req.url === '/data') { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({name: 'Node'})); } else if (req.url === '/info') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Information'); } else { res.writeHead(404); res.end('Not Found'); } sets correct headers and usesJSON.stringifyfor JSON data. Other options misuse content types or omit headers.Final Answer:
correctly sets headers and responses for both routes -> Option AQuick Check:
Set correct Content-Type and stringify JSON [OK]
Hint: Set Content-Type and stringify JSON for JSON responses [OK]
Common Mistakes:
- Sending JSON object directly without stringify
- Mixing content types for routes
- Omitting status codes or headers
