我试图使用流将数据发送到带有Hapi的浏览器,但无法理解我们的方法。具体来说,我使用的是请求模块。根据文档,reply对象接受流,因此我尝试了:
reply(request.get('https://google.com'));抛出一个错误。在文档中,它说流对象必须与streams2兼容,所以我尝试:
reply(streams2(request.get('https://google.com')));这并不会引发服务器端错误,但是在浏览器中,请求永远不会加载(使用chrome)。
然后我试了一下:
var stream = request.get('https://google.com');
stream.on('data', data => console.log(data));
reply(streams2(stream));并且在控制台中输出数据,所以我知道流不是问题,而是Hapi。我怎么才能在Hapi工作呢?
发布于 2015-07-04 15:57:40
尝试使用Readable.wrap
var Readable = require('stream').Readable;
...
function (request, reply) {
var s = Request('http://www.google.com');
reply(new Readable().wrap(s));
}使用Node 0.10.x和hapi 8.x.x进行测试。在我的代码示例中,Request是节点请求模块,request是传入的hapi请求对象。
更新
另一种可能的解决方案是从Request侦听“反应”事件,然后使用http.IncomingMessage监听reply,这是一个正确的读取流。
function (request, reply) {
Request('http://www.google.com')
.on('response', function (response) {
reply(response);
});
}这需要更少的步骤,并且还允许开发人员在传输之前将用户定义的属性附加到流。这在设置200以外的状态代码时很有用。
发布于 2019-12-24 10:36:31
2020年
我找到了!!问题是gzip压缩
要仅为event-stream禁用它,需要向Happi服务器提供下一个配置
const server = Hapi.server({
port: 3000,
...
mime:{
override:{
'text/event-stream':{
compressible: false
}
}
}
});在处理程序中,我使用axios,因为它支持新的流2协议。
async function handler(req, h) {
const response = await axios({
url: `http://some/url`,
headers: req.headers,
responseType: 'stream'
});
return response.data.on('data',function (chunk) {
console.log(chunk.toString());
})
/* Another option with h2o2, not fully checked */
// return h.proxy({
// passThrough:true,
// localStatePassThrough:true,
// uri:`http://some/url`
// });
};https://stackoverflow.com/questions/31210950
复制相似问题