我是express.js和API调用的新手,我无法弄清楚为什么这会让我的服务器崩溃?基本上它会在第一次运行并渲染页面时运行,但随后崩溃服务器说:
TypeError: Cannot read property 'length' of undefined
for (var i = 0; i < data.businesses.length; i++) {
相关的代码部分:
router.get('/:term/:radius/:lat/:lng', function (req, res) {
var yelp = require("yelp").createClient({
consumer_key: "xxxx",
consumer_secret: "xxxx",
token: "xxxx",
token_secret: "xxxx"
});
yelp.search({
term: req.params.term,
radius_filter: req.params.radius,
ll: req.params.lat + ',' + req.params.lng
},
function (error, data) {
var businessesArr = [];
if (typeof data) {
for (var i = 0; i < data.businesses.length; i++) {
businessesArr.push({
name: data.businesses[i].name,
image_url: data.businesses[i].image_url
});
}
res.render('selection', {
businesses: businessesArr
});
// console.log(data);
} else {
console.log(error);
}
});
});
答案 0 :(得分:2)
这一行:
if (typeof data) {
始终会评估为true,因为它实际上会返回一个字符串,无论如何。
将其替换为:
if (data && data.businesses) {