http.createServer中的http.get()
函数没有响应。Node.js. Http.get()函数没有响应。
我写了一个小片段来检索JSON数据,当用户发送请求到服务器。这是我的代码。
var http = require('http');
var x = '';
http.createServer(function (request,response) {
http.get({
host:'query.yahooapis.com',
path:'/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22MSFT%22)&format=json&env=store%3A%2F%2Fdata tables.org%2Falltableswithkeys&callback=cbfunc'
}, function(res){
res.on('data',function(d){
x+=d.toString();
console.log(d.toString());
})
});
response.writeHead(200, {'Content-Type':'text/plain'})
var l = JSON.parse(x.substring(7,x.length-2));
response.end(l.query.results.quote[0].symbol + '');
}).listen(8080);
我收到错误:
undefined:0
SyntaxError: Unexpected end of input
at Object.parse (native)
at Server.<anonymous> (C:\Users\Lenovo\Documents\fetch.js:18:12)
at Server.emit (events.js:70:17)
at HTTPParser.onIncoming (http.js:1491:12)
at HTTPParser.onHeadersComplete (http.js:102:31)
at Socket.ondata (http.js:1387:22)
at TCP.onread (net.js:354:27)
至于我的想法。错误是由于x =''不是json所以它抛出一个错误。但是,当通过调用localhost:8080发送请求时,它应该在控制台上显示一些json文本而不是错误。我的目标是实时解析股票报价,所以我在请求发出时发出了获取请求,并将其结果设置为响应。
我想多一个片段用于获取数据
var http = require('http');
var x = '/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22MSFT%22)&format=json&env=store%3A%2F%2Fdata tables.org%2Falltableswithkeys&callback=cbfunc';
http.get({
host: 'query.yahooapis.com',
path: ''
},function(res){
res.on('data',function(d){
x+=d.toString();
console.log(d.toString());
})
});
http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/plain'})
var l=JSON.parse(x.substring(7,x.length-2));
response.end(l.query.results.quote[0].symbol+'');
}).listen(8080);
它的工作在控制台上精细显示JSON文本,但我想我会得到的数据,一旦当我部署它在服务器上而不是当用户请求数据。我怎样才能解决这个错误?
在你的第一个例子中,最后一行不应该在那里? – 2012-01-17 10:48:39