Node.js Express.js & REST APIs 4 — Questions and Answers
Question 1: Which Express built-in middleware parses URL-encoded form bodies?
- express.json()
- express.raw()
- express.urlencoded() (Correct answer)
- express.text()
Correct answer: express.urlencoded()
express.urlencoded() parses bodies with Content-Type application/x-www-form-urlencoded.
Question 2: In REST API design, which HTTP method should be used for a partial update of a resource?
- PUT
- POST
- PATCH (Correct answer)
- UPDATE
Correct answer: PATCH
PATCH is designed for partial modifications, while PUT replaces the entire resource.
Question 3: What is the role of the morgan middleware in an Express application?
- Authentication token validation
- HTTP request logging (Correct answer)
- Body parsing
- Rate limiting
Correct answer: HTTP request logging
Morgan is an HTTP request logger middleware that records request details to the console or a stream.
Question 4: How do you define a catch-all 404 handler in Express that runs after all other routes?
- app.error(404, fn)
- app.use('*', fn) placed before routes
- app.use(fn) placed after all route definitions (Correct answer)
- app.get('404', fn)
Correct answer: app.use(fn) placed after all route definitions
Middleware registered with app.use() after all routes runs only when no route matched the request.
Question 5: Which approach correctly protects an Express route so only authenticated users can access it?
- Using res.secure inside the handler
- Placing an auth middleware before the route handler (Correct answer)
- Setting app.set('auth', true)
- Using req.authenticated flag
Correct answer: Placing an auth middleware before the route handler
Chaining an authentication middleware before the handler enforces auth before any business logic runs.
Question 6: What does app.set('view engine', 'ejs') configure in Express?
- The JSON serializer
- The default template engine for res.render() (Correct answer)
- A middleware for static files
- The port Express listens on
Correct answer: The default template engine for res.render()
app.set('view engine') tells Express which template engine to use when res.render() is called.
Question 7: Which response header tells the client the format of the response body in a REST API?
- Accept
- Authorization
- Content-Type (Correct answer)
- X-Response-Format
Correct answer: Content-Type
The Content-Type response header describes the media type of the body, e.g. application/json.
Which Express built-in middleware parses URL-encoded form bodies?