Node.js Express.js & REST APIs 2 — Questions and Answers
Question 1: Which Express method registers middleware that runs for every incoming request regardless of path?
- app.use('/', fn)
- app.all('*', fn)
- app.use(fn) (Correct answer)
- app.route(fn)
Correct answer: app.use(fn)
app.use(fn) without a path mounts middleware at '/' which matches every request.
Question 2: What does the Express Router class primarily help you accomplish?
- Create a new HTTP server
- Modularize route definitions into mini-apps (Correct answer)
- Manage database connections
- Parse incoming JSON bodies
Correct answer: Modularize route definitions into mini-apps
express.Router() creates a mini-app that groups related routes and middleware for modularity.
Question 3: In a REST API, which HTTP status code should be returned when a resource is successfully created?
- 200 OK
- 204 No Content
- 201 Created (Correct answer)
- 202 Accepted
Correct answer: 201 Created
201 Created signals that the request succeeded and a new resource was created.
Question 4: What is the purpose of calling next(err) inside an Express middleware?
- Skips to the next route handler
- Passes control to the next error-handling middleware (Correct answer)
- Terminates the request silently
- Retries the current middleware
Correct answer: Passes control to the next error-handling middleware
Passing an argument to next() triggers Express's error-handling pipeline, skipping regular middleware.
Question 5: Which of the following correctly accesses a URL query parameter in Express?
- req.params.q
- req.body.q
- req.query.q (Correct answer)
- req.headers.q
Correct answer: req.query.q
req.query contains the parsed query string key-value pairs from the URL.
Question 6: When using express.json() middleware, what Content-Type header must the client send for the body to be parsed?
- application/x-www-form-urlencoded
- text/plain
- application/json (Correct answer)
- multipart/form-data
Correct answer: application/json
express.json() only parses requests with Content-Type: application/json.
Question 7: Which REST principle states that each request must contain all information needed to process it, with no server-side session state?
- Uniform Interface
- Statelessness (Correct answer)
- Cacheability
- Layered System
Correct answer: Statelessness
Statelessness means the server stores no client context between requests; each is self-contained.
Which Express method registers middleware that runs for every incoming request regardless of path?