Express js 4x:req.params返回空对象

时间:2017-04-07 04:38:44

标签: javascript node.js express

尝试在快速js中获取URl参数,但得到空对象。

var password= require('./routes/password');
app.use('/reset/:token',password);

password.js

router.get('/', function(req, res, next) {
    console.log(req.params);
    res.send(req.params);
});

console.log(req.params)输出为{}

访问网址:http://localhost:3000/reset/CiVv6U9HUPlES3i0eUsNwK9zb7xVZpfHsQNuzMNWqLlGA4NJKoagwbcyiUZ8

3 个答案:

答案 0 :(得分:6)

默认情况下,嵌套路由器不会从其父路由器传递任何在mountpath中使用的参数。

在您的情况下,app是父路由器,它使用/reset/:token作为mountpath,而router是嵌套路由器。

如果您希望router能够访问req.params.token,请按以下步骤创建:

let router = express.Router({ mergeParams : true });

记录here

答案 1 :(得分:0)

相反,您可以使用中间件来记录路径参数:

const logger = (req, res, next)=>{
  console.log(req.params)
  res.send(req.params)
  next()//<----very important to call it.
};

app.use(logger); //<----use to apply in the app

router.get('/', (req, res, next)=>res.send('Logged.'));

答案 2 :(得分:0)

实际上你搞砸了一下。您必须将express的实例传递给您的模块。

<强> Server.js

//adding modules
require('./routes/password')(app);

<强> Password.js

module.exports = function(router) {
    router.get('/reset/:token', function(req, res, next) {
        console.log(req.params);
        res.send(req.params);
    });

    //and so on.. your routes go here
}