我对“x-ray”库的了解不多,但我认为问题在于它,因为它必须在可以返回响应数据之前异步发出请求。该文件说,如果你不设置路径作为参数传递给它返回一个可读流的写入功能,所以试试这个:
app.get('/', function(req, res) {
var stream = x('http://google.com', 'title').write(),
responseString = '';
stream.on('data', function(chunk) {
responseString += chunk;
});
stream.on('end', function() {
res.send(responseString);
});
});
您还需要启动服务器侦听特定端口上(3000在下面的例子):
const PORT = 3000;
app.listen(PORT, function() {
console.log("Server is listening on port " + PORT + ".");
}); // the callback function simply runs once the server starts
现在打开你的浏览器,然后导航到127.0.0.1:3000
或localhost:3000
,你会看到“谷歌”的出现!
ALSO:如果你想在一个完整的HTML页面(而不仅仅是发送它自己的字符串)使用响应数据,你可能要进一步探讨如何用玉做的快(或类似的)模板。而且,每当有人向您的服务器的相应路径发出请求时,此时的代码就会向Google进行刮擦;如果你只想刮一次Google,然后在服务器的响应中一次又一次地使用相同的字符串,你可能想要考虑如何实现这个(很简单!)。