How to detect whether a request will be handled by a route later in the stack? #5066
-
Sorry if this has already been addressed, but couldn't find anything in searching. What is the best way to know whether the URL in a request has a request handler associated before that handler is executed? In other words, given the express server below: const app = express();
app.use((req, res) => {
// check if req matches any routes below it in this file
});
app.get('/abc', (req, res) => {
// do some stuff
});
app.get('/xyz', (req, res) => {
// do some stuff
}); How can my first |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Hi. I don't know if there are better ways to do this, but here's one that might help you. You can iterate over const express = require('express')
const app = express();
app.use((req, res, next) => {
let hasRouteToHandle = false;
app._router.stack.forEach((stackItem) => {
// check if current rout path matches route request path
if (stackItem.route?.path === req.path) {
hasRouteToHandle = true;
}
});
if (hasRouteToHandle) {
console.log('Request will be handled by a route later in the stack')
} else {
// No matching route for this request
console.log('Request will not be handled')
}
next(); // to continue to next route
});
app.get('/abc', (req, res) => {
// do some stuff
});
app.get('/xyz', (req, res) => {
// do some stuff
});
app.listen(3000) |
Beta Was this translation helpful? Give feedback.
Hi. I don't know if there are better ways to do this, but here's one that might help you. You can iterate over
app._router.stack
property. This property stores a list of all routes registered in your app. Here is a example: