2017-08-29 155 views
0

我需要查找用戶的事件,但我無法檢索用戶,因爲我無法傳遞用戶標識來路由事件文件。將參數傳遞給路由文件

app.js:

var Router = express.Router(); 

Router.use("https://stackoverflow.com/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?

回答

0

我認爲這應該工作。
app.js:

var Router = express.Router(); 

Router.use("https://stackoverflow.com/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); 
    } 
    }); 
}); 
0

雖然Lazyexpert的答案是解決這個問題的方法,我發現我一直在尋找確切今天。

爲了從app.js通過UID

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

到另一條路線確保您的路由器包含{mergeParams:真正}

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