Bird
Raised Fist0
Node.jsframework~20 mins

Routing requests manually in Node.js - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Manual Routing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when a GET request is made to '/'?
Consider this Node.js server code that manually routes requests. What will the server respond with when a GET request is made to the root path '/'?
Node.js
import http from 'http';

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Home Page');
  } else if (req.method === 'GET' && req.url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('About Page');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

server.listen(3000);
AThe server responds with 'Not Found' and status 404.
BThe server responds with 'About Page' and status 200.
CThe server responds with 'Home Page' and status 200.
DThe server throws an error and crashes.
Attempts:
2 left
💡 Hint
Check the condition that matches the request method and URL.
📝 Syntax
intermediate
2:00remaining
Which option causes a syntax error in manual routing?
Look at these code snippets for routing requests manually in Node.js. Which one will cause a syntax error?
Aif (req.method === 'GET' && req.url === '/') { res.end('OK'); }
Bif (req.method === 'GET' && req.url === '/about') { res.end('About'); }
Cif (req.method === 'POST' && req.url === '/submit') { res.end('Submitted'); }
Dif req.method === 'GET' && req.url === '/' { res.end('OK'); }
Attempts:
2 left
💡 Hint
Check the syntax of the if statement.
🔧 Debug
advanced
2:00remaining
Why does this manual routing code always respond with 'Not Found'?
This Node.js server code is supposed to respond with 'Hello' on GET '/' requests, but it always responds with 'Not Found'. What is the cause?
Node.js
import http from 'http';

const server = http.createServer((req, res) => {
  if (req.method = 'GET' && req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

server.listen(3000);
AThe single '=' assigns 'GET' to req.method, but the condition is always false, so 'Not Found' is sent.
BThe single '=' assigns 'GET' to req.method, so the condition is always true and 'Hello' is sent.
CThe code throws a runtime error because req.method is read-only.
DThe server never starts because of a syntax error.
Attempts:
2 left
💡 Hint
Check the operator used in the if condition.
state_output
advanced
2:00remaining
What is the response when a POST request is made to '/submit'?
Given this manual routing code, what will the server respond with when a POST request is made to '/submit'?
Node.js
import http from 'http';

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Home');
  } else if (req.method === 'POST' && req.url === '/submit') {
    res.writeHead(201, { 'Content-Type': 'text/plain' });
    res.end('Submitted');
  } else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  }
});

server.listen(3000);
AThe server responds with 'Submitted' and status 201.
BThe server responds with 'Home' and status 200.
CThe server responds with 'Not Found' and status 404.
DThe server throws an error because POST is not handled.
Attempts:
2 left
💡 Hint
Check the condition that matches POST requests to '/submit'.
🧠 Conceptual
expert
2:00remaining
What is a key limitation of manual routing in Node.js HTTP servers?
When manually routing requests in Node.js using the http module, what is a main limitation compared to using a routing framework?
AManual routing requires writing repetitive code for each route, making it hard to scale and maintain.
BManual routing automatically handles query parameters and middleware, which can cause unexpected behavior.
CManual routing prevents the server from handling concurrent requests efficiently.
DManual routing forces the use of synchronous code, blocking the event loop.
Attempts:
2 left
💡 Hint
Think about code complexity and maintenance.

Practice

(1/5)
1. What is the main purpose of checking req.url in a Node.js server without frameworks?
easy
A. To decide how to respond to different request paths
B. To parse the request body automatically
C. To connect to a database
D. To handle user authentication

Solution

  1. Step 1: Understand the role of req.url

    req.url contains the path requested by the client, like '/home' or '/about'.
  2. Step 2: Purpose of checking req.url

    By checking req.url, the server can decide which content or response to send back.
  3. Final Answer:

    To decide how to respond to different request paths -> Option A
  4. Quick 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
A. res.status(200).send('Hello');
B. res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello');
C. res.sendStatus(200).send('Hello');
D. res.write(200, 'Hello');

Solution

  1. 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.
  2. Step 2: Check each option

    res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello'); uses writeHead and end correctly. The second and third options use Express methods, not native Node.js. res.write(200, 'Hello'); is invalid syntax.
  3. Final Answer:

    res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello'); -> Option B
  4. Quick 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
A. Error: Cannot read property 'writeHead' of undefined
B. Not Found
C. Hello World
D. Server crashes

Solution

  1. Step 1: Check the request URL condition

    The code checks if req.url === '/hello'. If true, it sends 'Hello World' with status 200.
  2. Step 2: Determine output for '/hello'

    Since the request is '/hello', the first branch runs, sending 'Hello World'.
  3. Final Answer:

    Hello World -> Option C
  4. Quick 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
A. Missing res.end() call
B. server.listen() missing port number
C. Incorrect header format in writeHead
D. Using assignment (=) instead of comparison (===) in if condition

Solution

  1. Step 1: Check the if condition syntax

    The condition uses req.url = '/test', which assigns instead of compares. This always evaluates to true.
  2. Step 2: Identify correct comparison operator

    It should be req.url === '/test' to compare values properly.
  3. Final Answer:

    Using assignment (=) instead of comparison (===) in if condition -> Option D
  4. Quick 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
A. 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'); }
B. if (req.url === '/data') { res.end({name: 'Node'}); } else if (req.url === '/info') { res.end('Information'); } else { res.end('Not Found'); }
C. if (req.url === '/data') { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('{"name":"Node"}'); } else if (req.url === '/info') { res.writeHead(200, {'Content-Type': 'application/json'}); res.end('Information'); } else { res.writeHead(404); res.end('Not Found'); }
D. if (req.url === '/data') { res.writeHead(404); res.end('Not Found'); } else if (req.url === '/info') { res.writeHead(200); res.end('Information'); }

Solution

  1. 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.
  2. 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 uses JSON.stringify for JSON data. Other options misuse content types or omit headers.
  3. Final Answer:

    correctly sets headers and responses for both routes -> Option A
  4. Quick 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