我正在对Zomato API进行两个API调用: 1)首先,我从用户输入城市名称,并从API获取Entity_Id和Entity_type参数。 2)我使用entity_Id和entity_type并进行另一个API调用,以从该API获取餐厅数据。
此代码可以正常使用一次,即我打开登录页面并输入城市名称,并显示我要正确显示的内容。
但是,如果我回击并输入另一个城市,则会遇到以下错误,并且我的应用程序崩溃。
我不知道为什么会这样。
var options = {
url : "https://developers.zomato.com/api/v2.1/",
headers : {
"user-key" : "//myAPIKeyHere"
}
};
app.get("/",function(req, res) {
res.render("search.ejs");
})
app.get("/restaurants",function(req,res){
console.log(req.query.search);
var cityName = req.query.search;
var cityArray = cityName.split(" ");
var cityAdd = cityArray[0];
if(cityArray.length>1){
for(var i =1;i<cityArray.length;i++){
cityAdd = cityAdd+"%20"+cityArray[i]
}
}
var ans= new Array();
options.url = options.url + "locations?query="+cityAdd;
request(options,function(error, response, body) {
if(!error && response.statusCode == 200){
var data = JSON.parse(body);
ans.push(data["location_suggestions"][0]["entity_id"])
ans.push(data["location_suggestions"][0]["entity_type"])
// res.send(ans);
options.url = "https://developers.zomato.com/api/v2.1/search?entity_id="+ ans[0]+ "&entity_type="+ans[1]+"&sort=rating&order=desc";
request(options,function(error2,response2,mainBody){
if(!error2 && response2.statusCode==200){
var newdata = JSON.parse(mainBody);
res.render("results.ejs",{data:newdata});
}
else{
console.log(error2);
res.send("Error Occured");
}
});
}
else{
ans.push(0)
ans.push(0)
console.log(error)
console.log("EERRRRRRRRRRRR")
return ans
}
})
});
错误:
/home/ubuntu/environment/zomato/app.js:40
ans.push(data["location_suggestions"][0]["entity_id"])
^
TypeError: Cannot read property '0' of undefined
at Request._callback (/home/ubuntu/environment/zomato/app.js:40:50)
at Request.self.callback (/home/ubuntu/environment/zomato/node_modules/request/request.js:185:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/home/ubuntu/environment/zomato/node_modules/request/request.js:1161:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (/home/ubuntu/environment/zomato/node_modules/request/request.js:1083:12)
at IncomingMessage.g (events.js:292:16)
at emitNone (events.js:91:20)
通常我每天刷新1000个API调用时,它应该可以工作多次。