我是node.js的新手我试图实现example。当我运行node app.js
时,我收到地图错误,如下所示:
错误
oneadmin@openflow1:~/Desktop/test-projects/nodejs/example$ node app.js
info - socket.io started
/home/oneadmin/Desktop/test-projects/nodejs/example/app.js:17
io.sockets.emit('tweets', obj.results.map(function (v) { return v.text; })
^
TypeError: Cannot read property 'map' of undefined
at Request._callback (/home/oneadmin/Desktop/test-projects/nodejs/example/app.js:17:42)
at Request.self.callback (/home/oneadmin/Desktop/test-projects/nodejs/example/node_modules/request/main.js:122:22)
at Request.EventEmitter.emit (events.js:107:17)
at Request.<anonymous> (/home/oneadmin/Desktop/test-projects/nodejs/example/node_modules/request/main.js:655:16)
at Request.EventEmitter.emit (events.js:126:20)
at IncomingMessage.<anonymous> (/home/oneadmin/Desktop/test-projects/nodejs/example/node_modules/request/main.js:617:14)
at IncomingMessage.EventEmitter.emit (events.js:126:20)
at _stream_readable.js:895:16
at process._tickCallback (node.js:343:11)
app.js
var sio = require('socket.io')
, http = require('http')
, index = require('fs').readFileSync(__dirname + '/index.html')
, request = require('request')
var app = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(index);
})
, io = sio.listen(app);
setInterval(function () {
request({
url: 'http://search.twitter.com/search.json?q=today'
}, function (err, res, data) {
var obj = JSON.parse(data);
io.sockets.emit('tweets', obj.results.map(function (v) { return v.text; }));
});
}, 2000);
io.sockets.on('connection', function (socket) {
socket.broadcast.emit('someone connected');
socket.on('some event', function () {
console.log('I got an event');
});
});
app.listen(3000);
的index.html
<!doctype html>
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
var socket = io.connect();
$(function () {
socket.on('tweets', function (tweets) {
$.each(tweets, function (i, tweet) {
$('#tweets').prepend($('<li>').text(tweet));
});
});
socket.on('someone connected', function () {
$('body').prepend('<p>Someone just connected!</p>');
});
socket.emit('some event');
});
</script>
</head>
<body>
<h1>Tweets</h1>
<ul id="tweets"></ul>
</body>
</html>
任何人都帮我删除此错误 提前谢谢!
答案 0 :(得分:0)
您可能需要在使用之前检查返回的值:
if (obj && obj.results) {
io.sockets.emit('tweets', obj.results.map(function (v) {
return v.text;
}));
}
但真正的问题是:为什么obj.results未定义?我检查了网址http://search.twitter.com/search.json?q=today并返回了此信息:
{ 错误:[ { 消息:&#34; Twitter REST API v1不再处于活动状态。请迁移到API v1.1。 https://dev.twitter.com/docs/api/1.1/overview。&#34 ;, 代码:64 } ] }
这就是为什么obj.results未定义的原因。