Bird
Raised Fist0
Expressframework~10 mins

Controller pattern for route handlers in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Controller pattern for route handlers
Client sends HTTP request
↓
Express Router receives request
↓
Router calls Controller function
↓
Controller processes request
↓
Controller sends response
↓
Client receives response
The client sends a request, Express router directs it to a controller function, which processes and sends back a response.
Execution Sample
Express
import express from 'express';
const app = express();

// Controller function
const getUser = (req, res) => {
  res.send(`User ID: ${req.params.id}`);
};

app.get('/user/:id', getUser);
This code sets up a route '/user/:id' that uses a controller function to send back the user ID from the URL.
Execution Table
StepActionInputController StateResponse Sent
1Client sends GET /user/42GET /user/42WaitingNo
2Express router matches route/user/42WaitingNo
3Router calls getUser controller/user/42Processing req.params.id = '42'No
4Controller executes res.send/user/42Processed id '42'Yes: 'User ID: 42'
5Response sent to clientUser ID: 42DoneYes
💡 Response sent, request cycle complete
Variable Tracker
VariableStartAfter Step 3After Step 4Final
req.params.idundefined'42''42''42'
responseSentfalsefalsetruetrue
Key Moments - 3 Insights
Why does the controller get called after the router matches the route?
Because the router directs matching requests to the controller function as shown in execution_table step 3.
What does res.send do inside the controller?
It sends the response back to the client and ends the request cycle, as seen in execution_table step 4.
Why is req.params.id available inside the controller?
Express parses the URL parameters before calling the controller, so req.params.id holds the value from the URL, shown in variable_tracker after step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of req.params.id at step 3?
Aundefined
B'user'
C'42'
Dnull
💡 Hint
Check the 'Controller State' column at step 3 in the execution_table.
At which step does the response get sent to the client?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Look at the 'Response Sent' column in the execution_table.
If the route was '/user/:id/profile', how would the controller receive the id parameter?
AIn req.params.profile
BIn req.params.id as usual
CIn req.query.id
DIt would not be available
💡 Hint
Route parameters are always available in req.params by their name, as shown in variable_tracker.
Concept Snapshot
Controller pattern in Express:
- Define controller functions to handle requests
- Use Express router to map routes to controllers
- Controllers receive req and res objects
- Controllers process data and send responses
- Keeps route logic clean and organized
Full Transcript
In Express, the controller pattern means separating the code that handles requests into functions called controllers. When a client sends a request, Express router matches the route and calls the appropriate controller function. The controller receives the request and response objects, processes the request (like reading URL parameters), and sends back a response. This keeps the code organized and easy to manage. For example, a route '/user/:id' uses a controller that reads req.params.id and sends it back in the response. The execution table shows each step from receiving the request to sending the response. Variables like req.params.id change from undefined to the actual value as the request is processed.

Practice

(1/5)
1. What is the main purpose of using the controller pattern in Express route handlers?
easy
A. To separate route logic from routing setup for better organization
B. To combine all route handlers into a single file
C. To directly write SQL queries inside route handlers
D. To avoid using middleware functions in routes

Solution

  1. Step 1: Understand the controller pattern concept

    The controller pattern means moving the logic that handles requests out of the route definitions into separate functions or files.
  2. Step 2: Identify the benefit of separation

    This separation improves code organization, making it easier to read and maintain.
  3. Final Answer:

    To separate route logic from routing setup for better organization -> Option A
  4. Quick Check:

    Controller pattern = separation of concerns [OK]
Hint: Controllers keep route files clean and logic separate [OK]
Common Mistakes:
  • Thinking controllers combine all routes in one file
  • Believing controllers write database queries directly
  • Confusing controllers with middleware avoidance
2. Which of the following is the correct way to import and use a controller function named getUser in an Express route?
easy
A. router.get('/user', getUser());
B. router.get('/user', () => getUser);
C. router.get('/user', getUser => {});
D. router.get('/user', getUser);

Solution

  1. Step 1: Understand how to pass controller functions

    In Express, route handlers expect a function reference, not the result of calling the function.
  2. Step 2: Identify correct syntax

    Passing getUser without parentheses passes the function itself. Using parentheses calls it immediately, which is incorrect here.
  3. Final Answer:

    router.get('/user', getUser); -> Option D
  4. Quick Check:

    Pass function reference without () [OK]
Hint: Pass controller as function reference, no parentheses [OK]
Common Mistakes:
  • Calling the controller function immediately with ()
  • Using arrow functions incorrectly wrapping the controller
  • Returning the function instead of calling it
3. Given this controller function and route setup, what will be the response when a GET request is made to /hello?
const sayHello = (req, res) => {
  res.send('Hello from controller!');
};

router.get('/hello', sayHello);
medium
A. Hello from controller!
B. Error: sayHello is not a function
C. No response, request hangs
D. 404 Not Found

Solution

  1. Step 1: Analyze the controller function behavior

    The sayHello function sends a plain text response 'Hello from controller!' when called.
  2. Step 2: Check route setup correctness

    The route uses sayHello correctly as the handler for GET requests to '/hello'.
  3. Final Answer:

    Hello from controller! -> Option A
  4. Quick Check:

    Controller sends response text [OK]
Hint: Controller sends response, route calls it correctly [OK]
Common Mistakes:
  • Forgetting to call res.send inside controller
  • Passing controller incorrectly causing runtime error
  • Misreading route path causing 404
4. Identify the error in this Express controller pattern usage:
const userController = {
  getUser: (req, res) => {
    res.json({ name: 'Alice' });
  }
};

router.get('/user', userController.getUser());
medium
A. res.json should be res.send
B. Missing import statement for router
C. Calling userController.getUser() immediately instead of passing function
D. Route path should be '/users' not '/user'

Solution

  1. Step 1: Check how controller function is passed

    The code calls userController.getUser() immediately, which runs the function and passes its result, not the function itself.
  2. Step 2: Understand correct usage

    Express expects a function reference as the route handler, so it should be userController.getUser without parentheses.
  3. Final Answer:

    Calling userController.getUser() immediately instead of passing function -> Option C
  4. Quick Check:

    Pass function reference, not call it [OK]
Hint: Don't add () when passing controller to route [OK]
Common Mistakes:
  • Calling controller function instead of passing it
  • Confusing res.json and res.send (both valid here)
  • Assuming route path naming causes error
5. You want to organize your Express app using the controller pattern. You have multiple routes for users: getUser, createUser, and deleteUser. Which approach best follows the controller pattern for clean code?
hard
A. Put all route definitions and logic inside a single routes.js file without controllers
B. Define all user-related functions in a separate userController.js file and import them in the router file
C. Write all user route handlers directly inside the main app.js file
D. Use inline anonymous functions for each route in the router file

Solution

  1. Step 1: Understand controller pattern best practice

    Controllers group related route logic into separate files or modules to keep code organized and reusable.
  2. Step 2: Evaluate options for clean code

    Defining all user-related functions in a dedicated userController.js file and importing them into the router file follows the pattern well.
  3. Final Answer:

    Define all user-related functions in a separate userController.js file and import them in the router file -> Option B
  4. Quick Check:

    Separate logic into controller files [OK]
Hint: Group related handlers in controller files, import in routes [OK]
Common Mistakes:
  • Putting all logic in main app file making it messy
  • Mixing routes and logic in one file without separation
  • Using anonymous functions inline reduces reusability
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard