ExpressJS:如何从全局中间件转储 req.params
ExpressJS: how to dump req.params from a global middleware
我无法为 ExpressJS 编写一个非常简单的中间件来记录所有 req.params 到控制台。
似乎如果我将中间件添加到特定函数,它就可以工作,而早期 app.use () 中的相同代码不会在 req.params.
中获取任何数据
这是一个示例代码:
const express = require('express')
const app = express();
// Simply log the req.params to console
const middle = ( req, res, next ) =>
{
console.log ( "PARAMS: ", req.params );
next ();
};
// Trying to access req.params in a global middleware does not work
app.use ( middle );
app.get('/', function (req, res) {
res.send('hello, world!')
})
// Specifying middleware in mount point works
app.get ( "/hello/:world", middle, ( req, res ) =>
{
console.log ( "This works: ", req.params );
res.send ( 'hello' );
} );
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
它不能作为全局中间件工作,因为这个参数只存在于 url "/hello/:world"
中,并且 express 在运行这个特定的 url 中间件之前不会知道这个参数。
可以用process.nextTick
来解决
const middle = ( req, res, next ) => {
process.nextTick(() => console.log ( "PARAMS: ", req.params ));
next ();
};
我无法为 ExpressJS 编写一个非常简单的中间件来记录所有 req.params 到控制台。 似乎如果我将中间件添加到特定函数,它就可以工作,而早期 app.use () 中的相同代码不会在 req.params.
中获取任何数据这是一个示例代码:
const express = require('express')
const app = express();
// Simply log the req.params to console
const middle = ( req, res, next ) =>
{
console.log ( "PARAMS: ", req.params );
next ();
};
// Trying to access req.params in a global middleware does not work
app.use ( middle );
app.get('/', function (req, res) {
res.send('hello, world!')
})
// Specifying middleware in mount point works
app.get ( "/hello/:world", middle, ( req, res ) =>
{
console.log ( "This works: ", req.params );
res.send ( 'hello' );
} );
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
它不能作为全局中间件工作,因为这个参数只存在于 url "/hello/:world"
中,并且 express 在运行这个特定的 url 中间件之前不会知道这个参数。
可以用process.nextTick
来解决
const middle = ( req, res, next ) => {
process.nextTick(() => console.log ( "PARAMS: ", req.params ));
next ();
};