Node.js的Http.get()函数没有响应。

时间:2012-01-17 10:38:22

标签: javascript node.js

http.createServer中的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文本正常工作,但我认为当我在服务器上部署它时,我将获取一次数据,而不是在用户请求数据时。我该如何解决错误?

1 个答案:

答案 0 :(得分:3)

node.js是异步的。这意味着http.get将在某个时刻返回。您发送http.get请求,然后立即尝试操纵x请求完成后您唯一的写入{。}}。

基本上http.get当您致电x === ''时,因为JSON.parse回调直到稍后才会触发。

http.get

重要的是等到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%2Fdatatables.org%2Falltableswithkeys&callback=cbfunc' }, function(res) { res.on('data', function(d) { x += d.toString(); console.log(d.toString()); }); res.on('end', next); }); function next() { 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响应。