gpt4 book ai didi

javascript - 我如何在请求模块中进行response.write

转载 作者:行者123 更新时间:2023-12-03 12:02:42 25 4
gpt4 key购买 nike

我正在创建 HTTP 服务器,在内部我向雅虎财经网站发送请求并从中获取一些数据,我想要做的是将我从雅虎财经获得的数据打印到浏览器。问题是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();)。几乎所有浏览器都会在显示任何内容之前缓冲响应中的一些字节,因此在响应结束之前您不会看到尝试打印某些内容

如果您使用 cURL 之类的内容,您将在响应结束之前立即看到尝试打印某些内容

关于javascript - 我如何在请求模块中进行response.write,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25341689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com