Node.js Course
Node.js
/
Beginner

Routing

Definition

Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method.

Explain Like I'm New

Routing is the hallway of doors in an office building. If a user walks in and wants to see their profile, the router directs them to the `/profile` door. If they want to delete an item, the router directs their `DELETE` request to the `/cart/delete` door.

Real World Example

Creating dynamic URL segments. When you visit `twitter.com/elonmusk`, 'elonmusk' isn't hardcoded into the server. The route is set up as `/users/:username`, and Express automatically extracts 'elonmusk' as a variable for you to look up in the database.

Common Use Cases

  • •API endpoint architecture
  • •Handling URL parameters and query strings

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • How do you capture dynamic variables in a URL like `/users/123`?

intermediate

  • What is the difference between `req.params` and `req.query`?

Flash Cards

Question

How to capture variables?

Click to reveal answer
Answer

Using a colon `:` in the route definition. E.g., `app.get('/users/:id')`. The value is then available inside `req.params.id`.

Question

req.params vs req.query?

Click to reveal answer
Answer

`req.params` grabs variables embedded directly in the path (e.g., `/users/:id`). `req.query` grabs optional variables appended to the end of the URL after a question mark (e.g., `/users?sort=desc`).