[英]Node application crashing after receiving JSON, but not before sending it.
所以我有一個嘗試創建的node.js應用程序,其中一部分是擴展到reddit的api並從URL獲取JSON,將其存儲在URL中並發送它收集的內容。 它完成所有這些但是在發出它找到的對象數組后,應用程序崩潰並出現錯誤
TypeError: Cannot read property 'children' of undefined
這對我沒有意義,因為它已經找到了這些值並將它們用於輸出。 知道什么可能是錯的嗎?
var express = require("express"),
restler = require("restler");
var app = express.createServer();
app.all('/:subreddit', function(req, res){
restler.get("http://www.reddit.com/r/"+ req.params.subreddit + ".json").on('complete', function(reddit){
var reddit_data = reddit.data.children;
var titles = new Array();
var i = 0;
while (i<5){
titles[i] = i+": " + reddit_data[i].data.title;
i++
}
res.send(titles);
});
});
app.listen(14042);
console.log("redSMS listening on 14042");
問題是你接受每個請求並將其傳遞給Reddit。
如果瀏覽器轉到http://localhost/bmw
,則express會將其傳遞給reddit並顯示http://www.reddit.com/r/bmw.json
的結果。 到現在為止還挺好。
然后瀏覽器執行它始終執行的操作,轉到http://localhost/favicon.ico
,它傳遞給Reddit,如http://www.reddit.com/r/favicon.ico.json
,給出404並且沒有結果。 當您嘗試訪問children
這一結果的,你得到的崩潰。
對“complete”事件處理程序的回調傳遞了2個參數,而不是一個。 第一個是“結果”,第二個是“響應”對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.