无法访问JSON API并给我引用错误

问题描述 投票:-1回答:1

我在尝试访问以下API formula one API时收到引用错误

我得到的错误是我无法访问MRData。我使用过JSON编辑器,我相信我有正确的途径。以下是发布请求。

app.get('/about', function(req, res){
res.render('about', {standings: null});
});

app.post('/about', function(req, res){
var year = req.body.Year;

var url = `http://ergast.com/api/f1/${year}/driverstandings.json?callback=`
request(url, function (err, response, body){
  if(err){
    res.render('about', {standings: null, error: 'Error, please try again'});
  } else {
    let standings = JSON.parse(body)
    if(standings.MRData === undefined) {
      res.render('about', {standings: null, error: 'Error, please try again'});
    } else {
      let firstName = MRData.StandingsTable.StandingsLists[0].DriverStandings[0].Driver.givenName
      let standingsText = `The winner of the formula 1 championship in the year ${MRData.StandingsTable.season} is ${firstName}`;
      res.render('about', {standings: standingsText, error: null});
    }
   }

 });

 });

任何帮助,将不胜感激。感谢您对此进行调查。

node.js express ejs
1个回答
0
投票

我能想到有1个语法错误和1个可选方案。

语法错误:

else部分,您直接引用MRData,而您应该通过standings.MRData引用它。对firstNamestandingsText都有

let firstName = standings.MRData.StandingsTable.StandingsLists[0].DriverStandings[0].Driver.givenName
let standingsText = `The winner of the formula 1 championship in the year ${standings.MRData.StandingsTable.season} is ${firstName}`;

另一个场景是req.body.Year可能是空白的,你正在使用它,所以控制台记录网址可能会导致一个解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.