You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Node.js中GET请求下campgrounds/:id路由无法正常工作的问题

解决Express路由campgrounds/:id无法正常工作的问题

我一眼就发现问题所在啦——你的目标路由路径少了最关键的开头斜杠!

问题根源

在Express框架中,路由路径必须以/开头才能正确匹配对应的URL路径。你当前的代码里是这样写的:

app.get("campgrounds/:id", function(req, res) {
    //find campground with id
    // Campground.FindById(req.param)
    // res.render("single.ejs");
    res.send("This will be the single page!");
})

这里的路径campgrounds/:id缺少开头的/,导致Express无法识别这个路由对应的URL规则。当你点击"more info"按钮跳转到campgrounds/[具体ID]时,服务器找不到对应的处理逻辑,自然无法正常响应。

另外补充个小细节:你当前的路由顺序是对的——/campgrounds/new放在/campgrounds/:id前面,避免了Express把new当成:id的参数值去匹配,这部分不用调整。

修正后的代码

只需要给路由路径加上开头的/即可:

//displaying specific campground
app.get("/campgrounds/:id", function(req, res) {
    //find campground with id
    // Campground.findById(req.params.id, function(err, foundCampground) {
    //     if(err) {
    //         console.log(err);
    //     } else {
    //         res.render("single.ejs", {campground: foundCampground});
    //     }
    // })
    res.send("This will be the single page!");
})

顺便帮你修正了注释里的小问题:Mongoose的查询方法是小写开头的findById,不是FindById;获取URL参数要用req.params.id,而不是req.param,这是你后续实现详情页功能时需要注意的点。

验证步骤

修改完成后重启服务器,再点击页面上的"more info"按钮,就能看到预期返回的文本"This will be the single page!"了。

内容的提问来源于stack exchange,提问作者miatech

火山引擎 最新活动