Facebook Pixel

What is Express Router and why use it?

Express Router creates modular route handlers. Create a router in routes/auth.js, define routes on it (router.post('/signup')), export it, and mount in app.js with app.use('/api', authRouter). This keeps app.js clean and groups related routes together.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Node.js Express Interview Questions Middleware, Routing, and Error Handling

Middleware is a function that runs during the request-response cycle. It receives (req, res, next) and can modify the request, send a response, or call next() to pass control. Types: application-level (app.use), router-level, built-in (express.json), error-handling (4 params), and third-party (cors, helmet).

app.use runs for ALL HTTP methods (GET, POST, PUT, DELETE) on the given path. app.get runs only for GET requests. Use app.use for middleware that should run regardless of method, app.get/post/put/delete for specific route handlers.

Error-handling middleware has 4 parameters (err, req, res, next). It's registered after all routes. When an error is thrown or next(err) is called, Express skips remaining middleware and goes to the error handler. Use an asyncHandler wrapper to catch async errors and pass them to next().

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.