Reputation: 51
I have nodejs express server, containing a generic middleware. There, I would like to get the route name. For example:
app.use(function (req, res, next) {
//using some npm pkg allowing me to run function after res.status was sent. This code runs at the very end of the request (after the response)
onHeaders(res, function () {
//console #1
console.log(req.route.path); })
next();
});
app.use((req, res, next) => {
//This code will run before the handler of the api, at the beginning of the request
//console #2
console.log(req.route.path);
});
app.post('/chnagePass/:id', handeler...) //etc
So the console #1, happening at the end of the request, prints /chnagePass/:id. console #2 doesn't work, req.route is undefined at this point.
But I would like to get this path name on console #2 (in my case, by the name of the route, I can decide what will be the timeout from some configuration).
How could I get the route name at this point (for example /chnagePass/:id) ? Is it possible?
Thank you very much!
Upvotes: 1
Views: 8093
Reputation: 752
The req.route
is populated only for middleware with a route. But since you are executing console#1 after the request, I believe the req
object has already been mutated by then.
I was able to reproduce what you see with this code
const express = require("express");
const app = express();
app.use(function(req, res, next) {
setTimeout(function() {
console.log("1: " + JSON.stringify(req.route));
}, 2000);
next();
});
app.use(function(req, res, next) {
console.log("2: Route: " + JSON.stringify(req.route));
console.log("2: Path: " + req.originalUrl);
next();
});
app.get("/magic/:id", function(req, res) {
console.log("3: " + JSON.stringify(req.route));
res.send("Houdini " + req.params.id);
});
app.listen(3300, function() {
console.log("Server UP!");
});
You can still get the exact path of the request by accessing req.originalUrl
like in the code above but that gives you the exact path used and not the matcher defined.
Upvotes: 1