无法访问JSON API并给我参考错误

时间:2019-03-05 20:32:11

标签: node.js express ejs

尝试访问以下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});
    }
   }

 });

 });

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

1 个答案:

答案 0 :(得分: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,而您正在使用该地址,因此控制台记录网址可能会导致解决方案。