我确定我的app.js存在问题,但是我不确定逻辑错误是什么。只是一点点的背景知识,我对NodeJS还是陌生的,因此决定使用COVID数据会很不错。
现在我对https://disease.sh/v2/all进行了api调用
返回
{
"updated": 1588719012878,
"cases": 3721393,
"todayCases": 78122,
"deaths": 257867,
"todayDeaths": 5626,
"recovered": 1238537,
"active": 2224989,
"critical": 49319,
"casesPerOneMillion": 477,
"deathsPerOneMillion": 33,
"tests": 40264726,
"testsPerOneMillion": 5161,
"affectedCountries": 214
}
因此,我在app.js下编写了以下代码
const express = require("express");
const app = express();
const https = require("https");
const url = "https://disease.sh/v2/all";
app.get("/",function(req,res){
https.get(url, function(response){
console.log(response.statusCode)
response.on("data",function(data){
const covidData=JSON.parse(data);
const cases = covidData[0].cases;
res.send("hello "+cases);
})
})
})
app.listen(3000,function(){
console.log("listening at port 3000")
})
但是我在终端上看到的错误消息是
/Users/alfietorres/Desktop/corona/app.js:14
const cases = covidData[0].cases;
^
TypeError: Cannot read property 'cases' of undefined
at IncomingMessage.<anonymous> (/Users/alfietorres/Desktop/corona/ap
p.js:14:34)
at IncomingMessage.emit (events.js:198:13)
at IncomingMessage.Readable.read (_stream_readable.js:504:10)
at flow (_stream_readable.js:973:34)
at resume_ (_stream_readable.js:954:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
[nodemon] app crashed - waiting for file changes before starting...
答案 0 :(得分:3)
API返回的数据实际上是对象的JSON表示形式,而不是数组。因此,您将使用covidData.cases
访问cases
属性。