MEAN Express.js Middleware and Routing 2 — Questions and Answers
Question 1: What does the `express.static()` middleware do?
- Serves static files like HTML, CSS, and images from a directory (Correct answer)
- Generates static HTML from templates
- Caches dynamic responses as static files
- Validates static file MIME types
Correct answer: Serves static files like HTML, CSS, and images from a directory
express.static() is built-in middleware that serves files from a specified directory, handling file streaming, ETags, and cache headers automatically.
Question 2: How do you set the HTTP status code of a response in Express.js?
- res.status(404).send('Not Found') (Correct answer)
- res.setStatus(404)
- res.code(404)
- response.status = 404
Correct answer: res.status(404).send('Not Found')
res.status() sets the HTTP status code and returns the response object for chaining with send(), json(), or end().
Question 3: What is CORS and how is it commonly handled in an Express API?
- Cross-Origin Resource Sharing, handled with the cors npm middleware package (Correct answer)
- Client-Origin Request System, handled with helmet middleware
- Cross-Origin Route Sharing, handled in app.all()
- Content Origin Restriction Scheme, handled in package.json
Correct answer: Cross-Origin Resource Sharing, handled with the cors npm middleware package
CORS allows or restricts web applications from making requests to a different domain; the cors npm package adds the required HTTP headers automatically.
Question 4: Which Express.js method sends a JSON response with the correct Content-Type header?
- res.json() (Correct answer)
- res.send({})
- res.write(JSON.stringify())
- res.end(JSON.stringify())
Correct answer: res.json()
res.json() serializes the passed object to JSON, sets Content-Type to application/json, and sends the response in one call.
Question 5: What does `app.use()` do in Express.js when used without a path argument?
- Mounts middleware that runs for every incoming request (Correct answer)
- Defines a catch-all route for undefined paths
- Sets global app configuration
- Registers a default route handler
Correct answer: Mounts middleware that runs for every incoming request
When app.use() is called without a path, the middleware function is executed for every request to the application regardless of the route.
Question 6: How do you access query string parameters in Express.js (e.g., /search?q=mean)?
- req.query.q (Correct answer)
- req.params.q
- req.body.q
- req.search.q
Correct answer: req.query.q
Express automatically parses query string parameters from the URL and makes them available as properties of the req.query object.
What does the `express.static()` middleware do?