Discover how routing can turn your messy URL checks into clean, easy-to-manage code!
Why Routing requests manually in Node.js? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine building a website where every time a user clicks a link, you have to check the URL and decide what content to show by writing many if-else statements.
Manually checking URLs is slow, messy, and easy to make mistakes. It becomes hard to add new pages or fix bugs because the code is tangled and repetitive.
Routing libraries automatically match URLs to the right code, keeping your project organized and making it easy to add or change pages without confusion.
if (url === '/home') { showHome(); } else if (url === '/about') { showAbout(); } else { show404(); }
router.get('/home', showHome); router.get('/about', showAbout); router.use(show404);
It lets you build clear, scalable websites where each URL leads to the right content without messy code.
Think of an online store where URLs like '/products' and '/cart' automatically show the right pages without you writing complex checks for each one.
Manual URL checks get complicated and error-prone quickly.
Routing libraries organize URL handling cleanly.
This makes websites easier to build and maintain.
Practice
req.url in a Node.js server without frameworks?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]
- Thinking req.url parses request body
- Confusing req.url with database connection
- Assuming req.url handles authentication
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]
- Using Express methods in plain Node.js
- Calling res.write without headers
- Incorrect method names like res.sendStatus
/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);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]
- Assuming default response is 'Hello World'
- Confusing 404 and 200 responses
- Expecting server error without syntax issues
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);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]
- Confusing assignment and comparison operators
- Forgetting to call res.end()
- Incorrect header object syntax
/data and plain text at /info. Which code snippet correctly implements this?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]
- Sending JSON object directly without stringify
- Mixing content types for routes
- Omitting status codes or headers
