我写了两个不同的Express路由请求,它们引用一个对象(该对象具有与每个电影相关的电影和数据)。它们应该显示不同的结果,但结构上完全相同。但是,一种有效,而另一种无效。这是代码:
按标题的电影
app.get("/movies/:title", (req, res) => {
res.json(Movies.find((movie) => {
return movie.title === req.params.title
}));
});
按类型的电影-这是无效的
app.get("/movies/:genre", (req, res) => {
res.json(Movies.find((movie) => {
return movie.genre === req.params.genre
}));
});
它们指的是以下对象:
let Movies = [{
id: 1,
title: "Night of the Living Dead",
genre: "Classical",
director: {
name: "George P. Romero",
bio: "Lorem ipsum dolor sit amet",
birth: "01/01/1900",
death: "01/01/1900"
},
imgUrl: "https://z.com/1/img/thumb.jpg"
},
{
id: 2,
title: "28 days later",
genre: "Apocalypse",
director: {
name: "Danny Boyle",
bio: "Lorem ipsum dolor sit amet consectetur",
birth: "01/01/1900",
death: "01/01/1900"
},
imgUrl: "https://z.com/2/img/thumb.jpg"
},
{
id: 3,
title: "Cell",
genre: "Apocalypse",
director: {
name: "Christopher Hatton",
bio: "ipsum dolor sit",
birth: "01/01/1900",
death: "01/01/1900"
},
imgUrl: "https://z.com/3/img/thumb.jpg"
}
];
第一个对请求localhost:8080 / movies / Lorem Ipsum正常工作,但是第二个对请求localhost:8080 / movies / Classical或其他任何请求均无效。
Express和文件顶部的应用程序的功能调用正常(它适用于第一个路由请求。
我很感谢任何启发。预先感谢您的可用性。
这是因为您在两条路线上使用了相同的模式。您尝试使用以下模式匹配两条路由:/movies/:parameter
。对于每个请求,Express都会尝试将请求路径与应用程序中注册的URL进行匹配。对于给定的示例:
/movies/Lorem Ipsum # Match the /movies/:title
/movies/Classical # Match the /movies/:title
为什么?因为路线/movies/:title
是声明顺序中的第一条路线。该参数的名称不计在内,因为在发送请求时,express不知道“ Lorem ipsum”为title
,而“ Classical”为genre
!仅在您的处理程序中使用req.params.title
作为示例,才可以在路由声明中使用参数名称。
更改您的模式,请改为使用查询(https://expressjs.com/fr/api.html#req.query)!您可以使用以下形式:
GET /movies?genre=Classical
GET /movies?title=Lorem%20Ipsum
您将拥有这样的路线:
app.get('/movies', (req, res) => {
if (req.query.title)
// do title research
else if (req.query.genre)
// do genre research
...
});
玩得开心!