简体   繁体   English

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

[英]Express js 4x :req.params returns empty object

Trying to get URl parameters in express js,but got empty object. 试图在快递js中获取URl参数,但得到空对象。

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

password.js password.js

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

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

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

By default, nested routers do not get passed any parameters that are used in mountpaths from their parent routers. 默认情况下,嵌套路由器不会从其父路由器传递任何在mountpath中使用的参数。

In your case, app is the parent router, which uses /reset/:token as a mountpath, and router is the nested router. 在您的情况下, app是父路由器,它使用/reset/:token作为mountpath, router是嵌套路由器。

If you want router to be able to access req.params.token , create it as follows: 如果您希望router能够访问req.params.token ,请按如下所示创建它:

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

Documented here . 记录在这里

Instead you can use a middleware to log the path params: 相反,您可以使用中间件来记录路径参数:

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.'));

Actually you messed it up a little bit. 实际上你搞砸了一下。 You have to pass instance of express to your module. 您必须将express实例传递给您的模块。

Server.js : Server.js

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

Password.js : 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM