Bird
0
0

In a REST API built with Express.js, you want to handle all unknown routes by returning a 404 JSON response with a message. Which middleware function correctly implements this?

hard📝 Application Q9 of 15
Rest API - HTTP Status Codes
In a REST API built with Express.js, you want to handle all unknown routes by returning a 404 JSON response with a message. Which middleware function correctly implements this?
Aapp.use((req, res) => { res.status(404).json({ error: 'Not Found' }); });
Bapp.get('*', (req, res) => { res.sendStatus(404); });
Capp.use((err, req, res, next) => { res.status(404).send('Not Found'); });
Dapp.all('*', (req, res) => { res.status(200).json({ error: 'Not Found' }); });
Step-by-Step Solution
Solution:
  1. Step 1: Understand middleware for unknown routes

    Middleware with app.use and no path catches all unmatched routes.
  2. Step 2: Check correct status and JSON response

    app.use((req, res) => { res.status(404).json({ error: 'Not Found' }); }); sets status 404 and sends JSON error message correctly.
  3. Final Answer:

    app.use((req, res) => { res.status(404).json({ error: 'Not Found' }); }); -> Option A
  4. Quick Check:

    Use app.use with res.status(404).json() for 404 middleware [OK]
Quick Trick: Use app.use with res.status(404).json() for 404 catch-all [OK]
Common Mistakes:
MISTAKES
  • Using app.get('*') which misses other methods
  • Sending 200 status with error message
  • Using error middleware for route not found

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes