MEAN Express.js Middleware and Routing 1 — Questions and Answers
Question 1: What is the correct order of arguments in an Express.js error-handling middleware function?
- (err, req, res, next) (Correct answer)
- (req, res, err, next)
- (req, err, res, next)
- (err, res, req, next)
Correct answer: (err, req, res, next)
Express identifies error-handling middleware by its four-argument signature (err, req, res, next) — the error object must be the first parameter.
Question 2: Which Express.js method is used to define a route that handles all HTTP methods?
- app.all() (Correct answer)
- app.any()
- app.use()
- app.route()
Correct answer: app.all()
app.all() matches all HTTP methods (GET, POST, PUT, DELETE, etc.) for the specified path, useful for authentication middleware on all routes.
Question 3: What does `express.json()` middleware do in an Express application?
- Parses incoming requests with JSON payloads and populates req.body (Correct answer)
- Serializes response objects to JSON automatically
- Validates JSON schema of request bodies
- Compresses JSON responses
Correct answer: Parses incoming requests with JSON payloads and populates req.body
express.json() is built-in middleware that parses the request body as JSON when Content-Type is application/json, making it available as req.body.
Question 4: How do you define a URL parameter in an Express route?
- app.get('/users/:id', handler) (Correct answer)
- app.get('/users/{id}', handler)
- app.get('/users/[id]', handler)
- app.get('/users/<id>', handler)
Correct answer: app.get('/users/:id', handler)
Express uses colon-prefixed segments like :id to define named URL parameters, which are then accessible via req.params.id.
Question 5: What is the purpose of calling `next()` in Express middleware?
- Passes control to the next matching middleware or route handler (Correct answer)
- Sends the response to the client
- Moves to the next HTTP request
- Skips remaining middleware in the chain
Correct answer: Passes control to the next matching middleware or route handler
Calling next() without arguments passes control to the next middleware function in the stack; calling next(err) skips to error-handling middleware.
Question 6: Which Express.js method creates a modular route handler that can be mounted at a path?
- express.Router() (Correct answer)
- express.route()
- app.module()
- app.group()
Correct answer: express.Router()
express.Router() creates a mini-application with its own middleware and routes that can be mounted on a specific path in the main app.
What is the correct order of arguments in an Express.js error-handling middleware function?