我无法为 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 ();
};
关于javascript - 来自全局中间件的 ExpressJS : how to dump req. 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54966152/