简体   繁体   English

Node.js Twitter流API

[英]Node.js twitter stream api

I am learning node.js using nettutplus introduction series. 我正在使用nettutplus简介系列学习node.js。 In this series there is a lesson for creating node.js app using twitter stream api, the code shown in video is exactly the same as the code i have written, however it doesn't work. 在本系列中,有一堂课是使用twitter流api创建node.js应用程序的,视频中显示的代码与我编写的代码完全相同,但是不起作用。

Here is my code 这是我的代码

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

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

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

request.end();

The error is get is this 错误是这个

undefined:1 未定义:1

^ ^

SyntaxError: Unexpected token < 语法错误:意外令牌<

at Object.parse (native)
at IncomingMessage.<anonymous> (C:\Users\monk\Desktop\folder\node\twitter.js:14:20)
at IncomingMessage.EventEmitter.emit (events.js:95:17)
at IncomingMessage.<anonymous> (_stream_readable.js:736:14)
at IncomingMessage.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
at IncomingMessage.Readable.push (_stream_readable.js:127:10)
at HTTPParser.parserOnBody [as onBody] (http.js:141:22)

I am using windows and cmd. 我正在使用Windows和cmd。

The code you are using is for old twitter api version 1. Twitter recently launched new version of api 1.1 and discontinued the older version. 您使用的代码适用于旧的twitter api版本1。Twitter最近启动了api 1.1的新版本,并停止了旧版本。 New twitter api requires you to authenticate every request and there are some changes in the authentication mechanism you can read in twitter developer site. 新的twitter api要求您对每个请求进行身份验证,并且可以在twitter开发人员站点中阅读的身份验证机制有所更改。 As for above error in script it is because you are trying to parse JSON.parse(chunk); 至于脚本中的上述错误,是因为您正在尝试解析JSON.parse(chunk);。 where chunk is html and you are getting those error. chunk是html,而您得到这些错误。 Try updating your code for latest version of twitter api. 尝试更新代码以获取最新版本的twitter api。 Thanks 谢谢

You are trying to parse a small chunk of response from the request, which may not be a valid JSON. 您正在尝试从请求中解析一小部分响应,该响应可能不是有效的JSON。 The complete response is a valid JSON. 完整的响应是有效的JSON。

It is streaming JSON constantly, delimited by endlines. 它不断地流送JSON,并以结尾行分隔。 And you have to handle those. 而且您必须处理这些。 You have to wait for the endlines then parse the recieved data. 您必须等待最终结果,然后解析收到的数据。 See an implentation here 在这里看到一个祈求

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

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