[英]How can i make a response.write in the request module
我正在创建HTTP服务器,并且在内部将请求发送到yahoo Finance网站并从中获取一些数据,我要做的是将从yahoo finance中获得的数据打印到浏览器中。 问题是response.write在请求中不起作用。 这是我的代码:
var http = require('http');
var request = require('request');
var cheerio = require('cheerio');
var util = require('util');
var host = "127.0.0.1";
var port = 1400;
var server = http.createServer(function (req, res) {
//writing the headers of our response
res.writeHead(200, {'Content-Type':'text/plain'});
// Variable Deceleration
// TODO: move from the global scope
var ticker = "IBM";
var yUrl = "http://finance.yahoo.com/q/ks?s=" + ticker;
var keyStr = new Array();
//
// The main call to fetch the data, parse it and work on it.
//
request(yUrl, function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
// the keys - We get them from a certain class attribute
var span = $('.time_rtq_ticker>span');
stockValue = $(span).text();
res.write("trying to print something");
console.log("Stock - " + ticker + " --> text " + stockValue );
}
}); // -- end of request --
res.write('Welcome to StockWach\n');
//printing out back to the client the last line
res.end('end of demo');
});
server.listen(port, host, function () {
console.log("Listening : " + host +":" + port);
});
您必须结束响应( res.end();
)。 几乎所有浏览器在显示任何内容之前都会缓冲响应中的一定数量的字节,因此直到响应结束之前,您不会看到trying to print something
的trying to print something
。
但是,如果使用cURL之类的内容,则会在响应结束之前立即trying to print something
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.