【问题标题】:Node.js - Express routing endpoint to Object Key Value inside arrayNode.js - 将路由端点快速路由到数组内的对象键值
【发布时间】:2021-07-30 21:20:26
【问题描述】:

我创建了一个本地服务器来学习和练习我的后端编码。现在它正处于成为“netflix”风格应用程序的早期阶段。我有一个代码:

app.get("/movies/:title", (req, res) => {
res.json(movies.find((movie) => {
    return movie.title === req.params.title
}));

});

当我输入这个 URL 时:localhost:8080/movies/:title(插入标题名称)它会从这个数组中返回所需的电影:

let movies = [
    //1
{
    title: 'Lord of the Rings',
    actor: 'Orlando',
    genre: 'adventure',
    director: 'person'

} ,
//2
{
    title: 'Harry Potter',
    actor: 'Daniel Radcliffe',
    genre: 'Fantasy',
    director: 'person',
    Movie_ID: "7"
} ,
//3
{
    title: 'Imaginaerum',
    actor: 'Toumas Holopainen',
    genre: 'Fiction',
    director: 'person',
    Movie_ID: "1"
} ,
//4
{
    title: 'Cloud Atlas',
    actor: 'Person',
    genre: 'Fantasy',
    director: 'person'
}

但是,当我尝试执行相同操作时,但在此 URL 中使用键值“actor”: localhost:8080/movies/:actor(替换为演员名称)

什么都没有出现。这是代码:

app.get("/movies/:actor", (req, res) => {
console.log(req.params)
res.json(movies.find(movie => {
    return movie.actor === req.params.actor
}));
});

非常感谢所有帮助!

【问题讨论】:

  • 不确定这是否是问题所在,但=== 区分大小写,因此您可能想说return move.actor.toLowerCase() === req.params.actor.toLowerCase();
  • /movies/:actor/movies/:title其实是同一个路由,所有的请求都会去最先声明的那个block。

标签: javascript node.js express url backend


【解决方案1】:

正如@Đăng Khoa Đinh 解释的那样,这些是相同的路线,因此您的代码不知道要使用哪个端点。

改一改:

/movies/actor/:actor/ 和另一个 /movies/title/:title 或类似的更改以使其正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2017-06-07
    • 1970-01-01
    • 2016-04-14
    相关资源
    最近更新 更多