最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

当id在单独的文件中定义时,req.params.id返回undefined

IT培训 admin 5浏览 0评论

当id在单独的文件中定义时,req.params.id返回undefined

当我使用req.params.id和mongoose时它会返回undefined。我相当肯定这是因为我在我的app.js中定义了id参数而不是我的路由文件。

路线文件:

//NEW - Form for adding new course
router.get("/new", function(req, res) {
    // find course by id
    Course.findById(req.params.id).exec(function(err, foundCourse) {
        if(err) {
            res.redirect("back");
        } else {
            //show template with correct id
            res.render("lectures/new", {course: foundCourse});
        }
    });
});

App.js文件:

app.use("/courses/:id/lectures", lectureRoutes);

有没有办法解决这个问题,以便我可以从路由文件中访问id参数?

编辑:我在浏览器中使用的路径:

http://localhost:7000/courses/5a4111286ae1111f541c3d88/lectures/new
回答如下:

为此,您必须启用名为mergeParams的选项。

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

请参阅文档here。

当id在单独的文件中定义时,req.params.id返回undefined

当我使用req.params.id和mongoose时它会返回undefined。我相当肯定这是因为我在我的app.js中定义了id参数而不是我的路由文件。

路线文件:

//NEW - Form for adding new course
router.get("/new", function(req, res) {
    // find course by id
    Course.findById(req.params.id).exec(function(err, foundCourse) {
        if(err) {
            res.redirect("back");
        } else {
            //show template with correct id
            res.render("lectures/new", {course: foundCourse});
        }
    });
});

App.js文件:

app.use("/courses/:id/lectures", lectureRoutes);

有没有办法解决这个问题,以便我可以从路由文件中访问id参数?

编辑:我在浏览器中使用的路径:

http://localhost:7000/courses/5a4111286ae1111f541c3d88/lectures/new
回答如下:

为此,您必须启用名为mergeParams的选项。

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

请参阅文档here。

发布评论

评论列表 (0)

  1. 暂无评论