ExpressJS:如何从全局中间件转储req.params

问题描述 投票:0回答:1

我无法为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!');
});
javascript node.js middleware
1个回答
1
投票

它不是作为全球中间件工作的,因为这个param只存在于url "/hello/:world"中,而express在运行这个特定的url中间件之前不会知道这个param。

你可以使用process.nextTick来解决它。

const middle = ( req, res, next ) => {
    process.nextTick(() => console.log ( "PARAMS: ", req.params ));

    next ();
};
© www.soinside.com 2019 - 2024. All rights reserved.