【发布时间】:2019-09-09 13:28:59
【问题描述】:
背景:
我有一个包含一些简单路由和路由器级中间件的快速应用程序。我想注册一个应用级中间件。
问题
在路由器级中间件中。我可以访问req.route 对象。但我无法访问应用程序级中间件中的同一个对象。
我可以理解这一点,因为在应用程序级中间件中,程序还没有在路由中。
但是有没有办法在全局中间件中获取req.route 对象或等效于req.route.path 的对象?
req.path 或 req.originalUrl 包含真正的 url 而不是路由路径。
示例
const express = require('express');
const app = express();
const port = 3232;
app.use((req, res, next) => {
const route = req.route; // It is an application level middleware, route is null
return next();
});
app.get('/test/:someParams', (req, res) => {
const route = req.route; // can access req.route here because it is a Router-level middleware
console.log(route.path)
console.log(req.path)
return res.send('test')
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
输出
请求:GET@localhost:3232/test/33333
/test/33333 // I don't need this.
/test/:someParams // This is what I want to get inside the Application-Level Middleware
替代解决方案
这个问题的替代解决方案如下
const express = require('express');
const app = express();
const port = 3232;
function globalMiddleware(req, res, next) {
const route = req.route;
console.log(route) // can access it
return next();
}
app.use((req, res, next) => {
const route = req.route; // It is an application level middleware, route is null
return next();
});
app.get('/test/:someParams', globalMiddleware, (req, res) => {
const route = req.route; // can access req.route here because it is a Router-level middleware
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
但是向我的每条路由注入相同的中间件听起来并不是一个聪明的解决方案。尤其适用于更大的应用程序。
路由器对象转储
{
"path":"/test/:someParams",
"stack":[
{
"name":"globalMiddleware",
"keys":[
],
"regexp":{
"fast_star":false,
"fast_slash":false
},
"method":"get"
},
{
"name":"<anonymous>",
"keys":[
],
"regexp":{
"fast_star":false,
"fast_slash":false
},
"method":"get"
}
],
"methods":{
"get":true
}
}
path 键是我想要得到的东西。请注意req.route.path与req.path不同
【问题讨论】:
标签: javascript node.js express middleware