将参数传递给路由文件

时间:2017-08-29 10:15:27

标签: node.js express

我需要查找用户的事件,但我无法检索用户,因为我无法传递用户ID来路由事件文件。

app.js:

var Router = express.Router();

Router.use("/users/:uid/events", events);

events.js:

Router.post("/",function (req,res) {
User.findOne({
    _id:req.params.uid
},function (err, foundUser) {
    if(err){
        res.json({success:false, message:"The user couldn't be found"});
    }else{
        console.log(req.params.uid);
        console.log(foundUser);
        var event = new Event();
        event.title = req.body.title;
        event.description = req.body.description;

        event.save(function (err) {
            if(err){
                console.log(err);
            }
        });

        foundUser.events.push(event);
    }
})
});

结果:

uid = undefined
foundUser = null

如何将uid参数传递给events.js?

2 个答案:

答案 0 :(得分:0)

我认为这应该有用 app.js:

var Router = express.Router();

Router.use("/users/", events);

events.js:

Router.post("/:uid/events", function (req,res) {
  User.findOne({
    _id:req.params.uid
  },function (err, foundUser) {
    if(err){
      res.json({success:false, message:"The user couldn't be found"});
    }else{
      console.log(req.params.uid);
      console.log(foundUser);
      var event = new Event();
      event.title = req.body.title;
      event.description = req.body.description;

      event.save(function (err) {
        if(err){
          console.log(err);
        }
      });

      foundUser.events.push(event);
    }
  });
});

答案 1 :(得分:0)

虽然Lazyexpert的答案是解决这个问题的一种方法,但我找到了我今天一直在寻找的东西。

为了从app.js传递uid

Router.use("/users/:uid/events", events);  

到另一条路线确保您的路由器包含{mergeParams:true}

var express = require('express');
var Router = express.Router({mergeParams:true});