简体   繁体   English

节点应用程序在收到JSON后崩溃,但在发送之前不会崩溃。

[英]Node application crashing after receiving JSON, but not before sending it.

So I have a node.js application im trying to create, and part of it is reaching out to reddit's api and getting the JSON from a url, storing it in a URL and sending out what it gathered. 所以我有一个尝试创建的node.js应用程序,其中一部分是扩展到reddit的api并从URL获取JSON,将其存储在URL中并发送它收集的内容。 It does all this but then after sending out the array of the objects it found, the application crashes with the error 它完成所有这些但是在发出它找到的对象数组后,应用程序崩溃并出现错误

    TypeError: Cannot read property 'children' of undefined

which doesnt make sense to me because it has already found those values and used them for the output. 这对我没有意义,因为它已经找到了这些值并将它们用于输出。 Any idea what could be wrong? 知道什么可能是错的吗?

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");

The problem is that you take every request and pass it to Reddit. 问题是你接受每个请求并将其传递给Reddit。

If the browser goes to, say http://localhost/bmw , express will pass it to reddit and show the results for http://www.reddit.com/r/bmw.json . 如果浏览器转到http://localhost/bmw ,则express会将其传递给reddit并显示http://www.reddit.com/r/bmw.json的结果。 So far so good. 到现在为止还挺好。

Then the browser does what it always does, goes for http://localhost/favicon.ico which passes to Reddit as http://www.reddit.com/r/favicon.ico.json , gives a 404 and no result. 然后浏览器执行它始终执行的操作,转到http://localhost/favicon.ico ,它传递给Reddit,如http://www.reddit.com/r/favicon.ico.json ,给出404并且没有结果。 When you try to access children of that result, you get the crash. 当您尝试访问children这一结果的,你得到的崩溃。

The callback to the "complete" event handler gets passed 2 parameters, not one. 对“complete”事件处理程序的回调传递了2个参数,而不是一个。 The first is the "result", and the second is the "response" object. 第一个是“结果”,第二个是“响应”对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM