连接到twitter api时,Node.js套接字挂起错误

时间:2013-02-23 07:02:01

标签: javascript node.js

当使用https通过基本身份验证连接到twitter流API时,我收到socket hang up错误。我认为在进行身份验证时会发生错误。

var https = require("https");
var options = {
        host: 'stream.twitter.com',
        path: '/1.1/statuses/filter.json?track=bieber',
        method: 'GET',
        headers: {
                "Authorization": "Basic " + new Buffer('UserName' + ":" + 'Password').toString("base64")
        }
}; //end of options


var request = https.request(options, function(response){
            var body = '';
             console.log('STATUS: ' + response.statusCode);
             console.log('HEADERS: ' + JSON.stringify(response.headers));

            response.on("data", function(chunk){
                    var tweet = JSON.parse(chunk);
                    console.log("Tweet " + tweet.text);
            });  // end of data

            response.on("end", function(){
                console.log("Disconnected!!");
            }); // end of end

            response.on("error", function(){
                console.log("error occured");
            }); // end of error
}); // end of request

request.on("error",function(error){
        console.log("Error: " + error.message);
                }); // end of error

当我尝试访问此网址时,它可以正常工作。

https://username:password@stream.twitter.com/1.1/statuses/filter.json?track=twitter

2 个答案:

答案 0 :(得分:5)

https.request(options, function(response){ }更改为https.get(options, function(response){ }感谢nodejs IRC上的Darrenlooby指出它。

答案 1 :(得分:3)

您可以使用https.request,但请务必添加:

request.end();

其中request是从https.request

返回的对象

有关示例,请参阅http://nodejs.org/api/https.html#https_https_request_options_callback

我有同样的问题,这解决了它:)