【发布时间】:2018-03-17 19:10:15
【问题描述】:
当尝试在我的删除(或更新)路线中使用 req.params.id 时,我收到了上述消息。这让我困惑了一段时间,我确信我的路线/对象在某个地方犯了错误。
将应用程序从 res.render("/campgrounds/ + req.params.id); 更改为 - res.render("/campgrounds");解决了这个问题,但不会像我希望的那样重新加载同一页面。从 req.params.id 访问露营地路线时,我无法理解为什么应用程序返回 undefined。
var express= require("express");
var router = express.Router();
var Comment = require("../models/comment");
var Campground = require("../models/campgrounds");
// COMMENTS EDIT ROUTE
router.get("/campgrounds/:id/comments/:comment_id/edit", function(req, res){
Comment.findById(req.params.comment_id, function(err, foundComment){
if(err){
console.log(err)
} else {
res.render("comments/edit", {campground_id: req.params.id, comment: foundComment})
}
})
})
// comment update
//campgrounds/:id/comments/:comment_id
router.put("/:comment_id", function(req, res){
Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment, function(err, updatedComment){
if(err){
console.log(err)
} else {
// KNOWN BUG - /campgrounds/ + req.params.id will return cast to boject failed for value undefined at path _id. having the app redirect to all campgrounds page as a work around
res.redirect("/campgrounds");
}
})
})
// DELETE ROUTER
router.delete("/:comment_id", function(req, res){
Comment.findByIdAndRemove(req.params.comment_id, function(err){
if(err){
res.redirect("back");
} else {
res.redirect("/campgrounds/" + req.params.id);
}
})
})
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
} else {
res.redirect("/login");
}
}
module.exports = router;
【问题讨论】:
-
你能给我请求的 url 你是如何从 server@Andy 访问 url 的
-
app.listen(process.env.PORT, process.env.IP, function(){ console.log("App is running"); })
标签: javascript node.js mongodb mongoose