Node.js Express.js & REST APIs 3 — Questions and Answers
Question 1: What does res.status(404).json({ error: 'Not found' }) do differently than res.json({ error: 'Not found' })?
- It sets the response body to 404
- It sends the status code as part of the JSON body
- It sets the HTTP status code to 404 before sending JSON (Correct answer)
- It ends the response without a body
Correct answer: It sets the HTTP status code to 404 before sending JSON
res.status() sets the HTTP status code, and json() then sends the response body with that code.
Question 2: In Express route definition app.get('/users/:id', handler), how do you access the dynamic segment?
- req.query.id
- req.body.id
- req.params.id (Correct answer)
- req.url.id
Correct answer: req.params.id
Named route segments prefixed with : are available on the req.params object.
Question 3: Which HTTP method is idempotent AND safe according to REST conventions?
- POST
- PUT
- DELETE
- GET (Correct answer)
Correct answer: GET
GET is both safe (no side effects) and idempotent (repeated calls yield the same result).
Question 4: What is the correct signature for an Express error-handling middleware?
- (req, res, next) => {}
- (err, req, res) => {}
- (err, req, res, next) => {} (Correct answer)
- (error, next) => {}
Correct answer: (err, req, res, next) => {}
Express identifies error-handling middleware by its four-parameter signature: err, req, res, next.
Question 5: When you call app.use('/api', router) where router has router.get('/users', fn), what full path triggers fn?
- /users
- /api
- /api/users (Correct answer)
- /api//users
Correct answer: /api/users
Express concatenates the mount path /api with the router's /users path to form /api/users.
Question 6: Which package is commonly used in Express apps to enable Cross-Origin Resource Sharing (CORS)?
- helmet
- morgan
- cors (Correct answer)
- body-parser
Correct answer: cors
The cors npm package adds CORS headers to responses and is the standard Express solution.
Question 7: What does res.sendStatus(204) send to the client?
- A JSON body with {status: 204}
- Status 204 with the default status message as the body (Correct answer)
- Status 204 with no body at all
- A redirect with code 204
Correct answer: Status 204 with the default status message as the body
res.sendStatus(204) sets the status code and sends the default status message ('No Content') as the body text.
What does res.status(404).json({ error: 'Not found' }) do differently than res.json({ error: 'Not found' })?