Express JS Express Middleware 1 — Questions and Answers
Question 1: What are the three arguments a standard Express middleware function receives?
- req, res, next (Correct answer)
- request, response, callback
- req, res, err
- req, next, done
Correct answer: req, res, next
Standard Express middleware receives the request object (req), response object (res), and the next() function.
Question 2: Which built-in Express middleware parses incoming JSON request bodies?
- express.json() (Correct answer)
- express.bodyParser()
- express.parseJSON()
- express.body()
Correct answer: express.json()
express.json() is the built-in middleware that parses incoming requests with JSON payloads.
Question 3: What does express.static() middleware do?
- Serves static files from a specified directory (Correct answer)
- Caches dynamic responses
- Sets static headers
- Compresses static assets
Correct answer: Serves static files from a specified directory
express.static() serves static assets like HTML, CSS, images, and JS from a given root directory.
Question 4: What type of middleware runs for every route regardless of path or method?
- Application-level middleware registered with app.use() without a path (Correct answer)
- Route-level middleware
- Error-handling middleware
- Third-party middleware
Correct answer: Application-level middleware registered with app.use() without a path
Calling app.use() without a path argument applies the middleware to every incoming request.
Question 5: How do you apply middleware only to a specific router in Express?
- Register it with router.use() on that router instance (Correct answer)
- Pass it as the first argument to app.listen()
- Use app.only()
- Set middleware.scope = 'router'
Correct answer: Register it with router.use() on that router instance
router.use() scopes middleware to only the routes handled by that specific router instance.
Question 6: What happens if a middleware function does not call next() or send a response?
- The request hangs and the client never receives a response (Correct answer)
- Express automatically sends a 200 OK
- The next middleware runs anyway
- Express throws an error
Correct answer: The request hangs and the client never receives a response
Without calling next() or sending a response, the request-response cycle stalls and the client times out.
What are the three arguments a standard Express middleware function receives?