【问题标题】:RESTful API, http get from couple of keysRESTful API,http 从几个键中获取
【发布时间】:2020-02-26 21:58:21
【问题描述】:

我是 node.js 的新手,我正在构建一个 RESTful API。 我有以下数据:

const matches = [ 
{
home_team: "Sutton United",
home_score: 0,
away_team: "Arsenal",
away_score: 0,
tournament: "fa",
start_time: "Monday 20th February 2017"
},
{
home_team: "Arsenal",
home_score: 0,
away_team: "Chelsea",
away_score: 0,
tournament: "fa",
start_time: "Monday 20th February 2017"
}
];

我正在尝试获取球队参加的所有比赛的响应,无论是主场还是客场。 因此,当我在寻找“阿森纳”时,我想要两场比赛。 我的代码如下所示:

app.get('/api/matches/:home_team'||'/api/matches/:away_team', (req, res) => {
const match = matches.find(c => (c.home_team === req.params.home_team || c.away_team === req.params.away_team))
if (!match) res.status(404).send('The match with the given id was not found');
res.send(match);});

这不是我想要的方式。 我该如何解决?

【问题讨论】:

    标签: node.js express http get


    【解决方案1】:

    使用过滤器代替查找:

    app.get('/api/matches/:team', (req, res) => {
    const match = matches.filter(c => (c.home_team === req.params.team || c.away_team === req.params.team));
    if (!match) 
       res.status(404).send('The match with the given id was not found');
    res.send(match);
    });
    
    

    【讨论】:

    • @Eusebius 也使用一条路线并与之比较。检查我更新的答案。
    猜你喜欢
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-12
    • 2020-05-31
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多