Node JS 忽略未定义的检查 [英] Node JS ignores undefined check
问题描述
我正在开发一个 NodeJs 应用程序,该应用程序从 FB 获取事件并将其放入本地数据库.对于 api 查询的第一页中的每个事件,这一切顺利,除了最后一个.
Im working on a NodeJs app that takes an event from FB and puts it into a local database. For every event in the first page of the api query this goes well, except for the last one.
我收到以下错误:
[2016 年 12 月 1 日,下午 1:48:39] 类型错误:无法读取属性名称"未定义的在传入消息.(/home/node/virgo/app.js:217:32)在 IncomingMessage.emit (events.js:129:20)在 _stream_readable.js:907:16在 process._tickCallback (node.js:372:11)
[December 1st 2016, 1:48:39 pm] TypeError: Cannot read property 'name' of undefined at IncomingMessage. (/home/node/virgo/app.js:217:32) at IncomingMessage.emit (events.js:129:20) at _stream_readable.js:907:16 at process._tickCallback (node.js:372:11)
刚刚结束
console.log(resultBody);
代码:
function addFBEvent(facebookId){
console.log("getting event: " + facebookId);
var options = {
hostname: 'graph.facebook.com',
port: 443,
path: '/v2.8/'+facebookId+'?fields=name,description,start_time,end_time,place,photos{images}&access_token={INSERT API ACCESS CODE HERE}',
method: 'GET'
};
https.request(options, function(res2) {
var resultBody = "";
res2.setEncoding('utf8');
res2.on('data', function (chunk) {
resultBody = resultBody + chunk;
});
res2.on('end', function () {
dbConnection = sql.createConnection({
host : settings.dbHost,
user : settings.dbUser,
password : settings.dbPassword
});
dbConnection.connect(function(err){
if(!err) {
console.log("Database is connected ... nn");
} else {
console.log("Error connecting database ... nn");
}
});
var json = JSON.parse(resultBody);
console.log(resultBody);
if (json != undefined){
var eventName = json.name;
var eventStart = json.start_time;
var eventEnd = json.end_time;
var eventDescription = json.description;
var eventPlace = json.place.name;
var eventPoster = json.photos.data[json.photos.data.length-1].images[0].source;
var eventId = json.id;
console.log("name: " + eventName + ", start: " + eventStart + ", end: " + eventEnd + ", place: " + eventPlace + ", Poster: " + eventPoster);
//console.log("Description: " + eventDescription);
dbConnection.query('INSERT INTO SVVirgo.activities(title, description, image, start, end, price, location, facebook) VALUES ("'+eventName+'","'+eventDescription+'","'+eventPoster+'","'+eventStart+'","'+eventEnd+'",0,"'+eventPlace+'","'+eventId+'")', function (err, result){
});
}
dbConnection.end();
})
}).end();
}
有关中断事件,请参阅图形 API 资源管理器:Graph API
See graph api explorer for the breaking event: Graph API
事件代码:1682486658666506
Event code: 1682486658666506
我尝试捕获未定义的 json 对象但没有成功,我也尝试使用此解决方案验证 json:Stackoverflow 验证 JSON javascript
I've tried catching the undefined json object with no luck, i've also tried to validate the json using this solution: Stackoverflow validate JSON javascript
推荐答案
代替 https.request
尝试使用 请求
.
Instead of https.request
try using request
.
它将为您提供解析的 JSON,而您不必手动完成.
It will give you parsed JSON and you won't have to do it manually.
如果你想像你一样手动完成,那么记得将 var json = JSON.parse(resultBody);
包裹在 try/catch 块中(或使用 tryjson
) 因为 JSON.parse
不能用于未知try/catch 之外的数据 - 它可以抛出异常.
If you want to do it manually like you do, then remember to wrap var json = JSON.parse(resultBody);
in a try/catch block (or use tryjson
) because the JSON.parse
cannot be used on unknown data outside of a try/catch - it can throw exceptions.
另一件事,不要在路由处理程序中打开数据库连接.您应该打开连接一次,然后在处理程序中使用它.有关详细信息,请参阅此答案.
Another thing, don't open you database connection in your route handlers. You should open the connection once and just use it in your handlers. See this answer for more info about it.
现在你正在连接到数据库,但你在连接回调之外继续,所以你运行从 var json = JSON.parse(resultBody);
before<开始的所有行/strong> 数据库连接已建立.
Right now you are connecting to the database but you continue outside of the connection callback, so you run all the lines beginning from var json = JSON.parse(resultBody);
before the DB connection is established.
另外,错误可能不是因为 json
未定义,而是因为 json.place
未定义.
Additionally, the error may be not because json
is undefined but because json.place
is undefined.
你可以改变这个:
var eventPlace = json.place.name;
为此:
var eventPlace = json.place && json.place.name;
您还必须在访问 json.photos.data
之前检查 json.photos
并测试 json.photos.data
是否是一个数组在你这样对待它之前(你可以这样做:
You must also check json.photos
before you access json.photos.data
and test if json.photos.data
is an array before you treat it as such (you can do it with:
if (json.photos && Array.isArray(json.photos.data)) {
// ...
}
基本上,在访问这些值之前,您需要确保它们是您想要的值.例如访问这个:
Basically, you need to make sure the values are what you want them to be before you access them. For example accessing this:
json.photos.data[json.photos.data.length-1].images[0].source
可能会在 json
未定义、json.photos
未定义、json.photos.data
未定义、 时失败>json.photos.data
不是数组,当 json.photos.data.length
为零时,当 json.photos.data[json.photos.data.length>-1]
未定义,当 json.photos.data[json.photos.data.length-1].images
未定义,当 json.photos.data[json.photos.data.length-1].images
不是数组,当 json.photos.data[json.photos.data.length-1].images
是数组但它是空的,或者当 json.photos.data[json.photos.data.length-1].images
是一个非空数组但 json.photos.data[json.photos.data.length-1].images[0].source
未定义.
can fail when json
is undefined, when json.photos
is undefined, when json.photos.data
is undefined, when json.photos.data
is not an array, when json.photos.data.length
is zero, when json.photos.data[json.photos.data.length-1]
is undefined, when json.photos.data[json.photos.data.length-1].images
is undefined, when json.photos.data[json.photos.data.length-1].images
is not an array, when json.photos.data[json.photos.data.length-1].images
is an array but it's empty, or when json.photos.data[json.photos.data.length-1].images
is a non-empty array but json.photos.data[json.photos.data.length-1].images[0].source
is undefined.
如您所见,您在这里做了很多假设.如果不满足这些假设,代码就会失败.
As you can see there are a lot of assumptions that you are doing here. When those assumptions are not met, the code will fail.
这篇关于Node JS 忽略未定义的检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!