我无法为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!');
});
答案 0 :(得分:1)
它不能用作全局中间件,因为此参数仅存在于URL "/hello/:world"
中,而express在他运行此特定的URL中间件之前不会知道该参数。
您可以使用process.nextTick
来解决它。
const middle = ( req, res, next ) => {
process.nextTick(() => console.log ( "PARAMS: ", req.params ));
next ();
};