Facebook Pixel

What is the difference between app.use and app.get?

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.

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).

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().

A wrapper function: const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next). It catches rejected promises from async route handlers and passes them to Express's error middleware, eliminating the need for try-catch in every handler.

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.