【问题标题】:Accessing a specific item through an api endpoint通过 api 端点访问特定项目
【发布时间】:2020-09-02 19:04:04
【问题描述】:

当直接在邮递员中传递 id 以进行测试请求时,我试图访问英雄的特定详细信息。但是,它会输出所有内容,而不仅仅是输出我请求的物品/英雄。

我做错了什么?

// overwatch hero detail
app.get("/hero/:id", (req, res) => {
  let detail = [
    {
        id: 1,
        real_name: "Hana Song",
        age: "19",
        nationality: "Korean",
        occupation: "Professional Gamer, Mech Pilot, Actress"
    },
    {
        id: 2,
        real_name: "Winston",
        age: "20",
        nationality: "",
        occupation: "Scientist"
    }
  ];
  res.json(detail)
});

【问题讨论】:

    标签: javascript glitch-framework


    【解决方案1】:

    你需要一个过滤功能:

    const id = req.params.id;
    const result  = detail.filter((item)=> item.id === id)
    return result[0]
    

    【讨论】:

      【解决方案2】:

      您应该使用 find 函数在数组中查找特定对象

      const result = detail.find(obj=>obj.id===id);
      res.json(result)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-18
        • 1970-01-01
        • 1970-01-01
        • 2020-07-11
        • 2020-02-07
        • 2015-10-01
        • 2020-01-28
        • 1970-01-01
        相关资源
        最近更新 更多