CodeBlanks Logo Icon CodeBlanks

Routing

Learn simple URL routing logic.

Routing

Routing means giving different responses based on the request path (req.url). The simplest way is checking the path with if conditions.

Example: if (req.url === "/") { res.end("Home"); } else if (req.url === "/about") { res.end("About"); } else { res.end("Unknown"); }. Here req.url gives the request path; each path produces a different response. The else branch provides a fallback for unknown paths. This is a simplified version of what frameworks like Express do behind the scenes; frameworks match the path with a more organized table.

Unknown paths

In routing it is good practice to always keep an else branch. This branch gives a fallback response for unmatched paths; this way no request hangs.

Example: if (req.url === "/") { res.end("Home"); } else { res.end("Unknown path"); }. A request to /about gets Unknown path. Usually unknown paths also set a 404 status: res.statusCode = 404; then res.end("Not found"). This clearly tells the user the path is invalid. statusCode is the response's HTTP status code; 200 means success, 404 means not found.

Practice Write two-path routing

Import the http module. Create a server with createServer. Inside the handler check req.url: if "/" call res.end("Home"), otherwise res.end("Unknown"). The ready-made code below starts the server and sends a request to "/".

Starter code

index.js
// Import the http module and create a server
// write here

server.listen(3000, () => {
  http.get("http://localhost:3000/", (res) => {
    let body = "";
    res.on("data", (c) => body += c);
    res.on("end", () => { console.log("Reply: " + body); server.close(); });
  });
});

Sample solution

index.js
const http = require("http");
const server = http.createServer((req, res) => {
  if (req.url === "/") { res.end("Home"); }
  else { res.end("Unknown"); }
});

server.listen(3000, () => {
  http.get("http://localhost:3000/", (res) => {
    let body = "";
    res.on("data", (c) => body += c);
    res.on("end", () => { console.log("Reply: " + body); server.close(); });
  });
});

Expected output

Yanıt: Ana sayfa

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which property is basic routing based on?

index.js
if (req.url === "/x") { ... }
  • req.method
  • res.end
  • req.url Correct answer
  • server.listen

Explanation: req.url gives the request path; routing uses it.

2 Match each path to its response

Term Meaning
"/" Home
"/about" About
else Unknown
req.url Request path

3 Complete the routing condition

Question
if (req.____ === "/") { res.end("Ana sayfa"); }
Answer
if (req.url === "/") { res.end("Ana sayfa"); }

Explanation: req.url holds the request path.

All lessons in Intermediate