Express JS Express Middleware 2 — Questions and Answers
Question 1: Which built-in Express middleware parses URL-encoded form data?
- express.urlencoded() (Correct answer)
- express.formData()
- express.form()
- express.parseForm()
Correct answer: express.urlencoded()
express.urlencoded() parses incoming requests with URL-encoded payloads, such as HTML form submissions.
Question 2: What is the signature of an Express error-handling middleware?
- (err, req, res, next) (Correct answer)
- (req, res, next, err)
- (err, req, res)
- (error, request, response, callback)
Correct answer: (err, req, res, next)
Error-handling middleware must declare exactly four parameters: err, req, res, and next, in that order.
Question 3: Which popular third-party middleware is used for logging HTTP requests in Express?
- morgan (Correct answer)
- winston
- bunyan
- log4js
Correct answer: morgan
morgan is the most widely used Express HTTP request logger middleware.
Question 4: What does the 'cors' middleware package primarily do in an Express app?
- Enables Cross-Origin Resource Sharing by setting appropriate HTTP headers (Correct answer)
- Compresses response bodies
- Parses cookies
- Handles authentication
Correct answer: Enables Cross-Origin Resource Sharing by setting appropriate HTTP headers
The cors middleware sets headers like Access-Control-Allow-Origin to allow or restrict cross-origin requests.
Question 5: How do you invoke the next error-handling middleware from a route by passing an error?
- next(err) with an error object or string (Correct answer)
- throw err
- res.error(err)
- next.error(err)
Correct answer: next(err) with an error object or string
Calling next() with any argument (except 'route' or 'router') triggers the error-handling middleware chain.
Question 6: What does passing the string 'route' to next() do in Express?
- Skips remaining handlers for the current route and moves to the next route (Correct answer)
- Redirects to a named route
- Throws a routing error
- Ends the middleware chain
Correct answer: Skips remaining handlers for the current route and moves to the next route
next('route') skips any remaining middleware registered on the current route and passes to the next matching route.
Which built-in Express middleware parses URL-encoded form data?