SyntaxError: Unexpected token <at Object.parse (native) in NodeJS

I am trying to track tweets via the Twitter Streams API using NodeJS, but I am facing this problem:

undefined:1

SyntaxError: Unexpected token <
    at Object.parse (native)
    at IncomingMessage.<anonymous> (C:\Users\ADiL-\Desktop\nodejs\twitter\tweets.js:1
7:20)

      

This is my code:

var https = require("https");

var option={
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(option,function(response){

var body = '';

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

response.on("end", function(){
    console.log("disconnected");
});

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

      

and when I remove the parsing and only show the chunk it gives this error:

<html>\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>\
n<title>Error 401 Unauthorized</title>
</head>
<body>
<h2>HTTP ERROR: 401</h2>
<p>Problem accessing '/1.1/statuses/filter.json?track=bieber'. Reason:
<pre>    Unauthorized</pre>
</body>
</html>

      

+3


source to share


1 answer


so no one answered, i did my best and i found a solution using the ntwitter module and it works, here is the code in case anyone stuck with it in the future ...

first of all install the ntwitter module using:

npm install ntwitter

      



and this is the code:

var twitter = require("ntwitter");

var t = new twitter({
consumer_key: ' ',
consumer_secret: ' ',
access_token_key: ' ',
access_token_secret: ' ' 
});

var i = 0;

t.stream(
'statuses/filter',
{track : ["awesome","nodejs","other_keywords"]},
function(data){
    data.on("data",function(tweets){
        i++;
        console.log("Tweet ",i," : ",tweets.text);
    });
}
);

      

0


source







All Articles