我正在尝试使用NodeJS通过Twitter Streams API跟踪推文,但我遇到了这个问题:
undefined:1
SyntaxError: Unexpected token <
at Object.parse (native)
at IncomingMessage.<anonymous> (C:\Users\ADiL-\Desktop\nodejs\twitter\tweets.js:1
7:20)
这是我的代码:
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();
当我删除解析并仅显示该块时,它会给出该错误:
<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>
答案 0 :(得分:0)
所以没有人回答我做了我的努力,我找到了一个解决方案,使用ntwitter模块,它可以工作,如果将来任何一个卡在其中的代码如下...
首先使用:
安装ntwitter模块npm install ntwitter
这是代码:
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);
});
}
);