简体   繁体   中英

Twitter stream api

I am trying to learn and understand nodejs. While trying to connect to api of Twitter stream and track tweets, I get following error :

 undefined:1

    <html>\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=ut
    ^
    SyntaxError: Unexpected token <
        at Object.parse (native)
        at IncomingMessage.<anonymous> (/home/ytsejam/public_html/nodejs/11/twitter.js:15:20)
        at IncomingMessage.emit (events.js:95:17)
        at IncomingMessage.<anonymous> (_stream_readable.js:764:14)
        at IncomingMessage.emit (events.js:92:17)
        at emitReadable_ (_stream_readable.js:426:10)
        at emitReadable (_stream_readable.js:422:5)
        at readableAddChunk (_stream_readable.js:165:9)
        at IncomingMessage.Readable.push (_stream_readable.js:127:10)
        at HTTPParser.parserOnBody [as onBody] (http.js:142:22)

here is my code which I try to connect :

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")
    }
};
var request = https.request('https://stream.twitter.com/1.1/statuses/filter.json?track=query', function(response){
    var body = '';
    response.on("data", function(chunk){
        var chunk = chunk.toString();
        try {
            var tweet = JSON.parse(chunk);
        } catch (err) {
             console.log("JSON parse error:" + err);
        } 


        console.log(tweet.text);
    });
    response.on("end",function(){
        console.log("Disconnected");
    });
});

request.end();

I did a research and tried to debug. my best guess is var tweet = JSON.parse(chunk); may cause problems. second option, I am missing oauth parameters.

Can you help me ? Thanks.

Edit :

I solved this using answer here Node.js and Twitter API 1.1

JSON.parse() is throwing a SyntaxError because the data it is trying to parse is HTML and not JSON.

In general, it's a good idea to wrap JSON.parse() in a try / catch block so you can handle those sorts of things gracefully.

(It is possible that there is a problem in your oauth stuff and it is failing to authenticate. So instead of getting JSON, you are getting an HTML page telling you that authentication has failed. But that is just a guess.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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