具有不同输出的类似 Express 路由请求

Similar Express routing requests with different outputs

我写了两个不同的 Express 路由请求,它们引用一个 Object(它有电影和与每部电影相关的数据)。它们应该显示不同的结果,但在结构上完全相同。但是,一个有效,另一个无效。这是代码:

按标题分类的电影

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
  }));
});

他们指的是以下object:

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和app的功能调用是可以的(它适用于第一个路由请求。

如有任何启发,我将不胜感激。预先感谢您的可用性。

这是因为您对两条路线使用了相同的模式。您尝试使用以下模式匹配两条路线:/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

    ...
});

玩得开心!