【问题标题】:Reading http/2 push stream fails with error -505读取 http/2 推送流失败并出现错误 -505
【发布时间】:2019-08-06 08:48:31
【问题描述】:

我正在尝试读取 http/2 推送流,但下面的代码失败并出现错误。当我在 Chrome 浏览器中使用相同的 URL 时,我会收到流服务器生成的“心跳”,并且也可以看到传入的数据。任何指针?我的目标只是读取服务器生成的所有 JSON 推送响应。

Error:
{ Error [ERR_HTTP2_ERROR]: Protocol error
    at Http2Session.onSessionInternalError [as error] (internal/http2/core.js:637:26)
  code: 'ERR_HTTP2_ERROR',
  name: 'Error [ERR_HTTP2_ERROR]',
  errno: -505 }

Node.JS 代码:

const http2 = require('http2');
const client = http2.connect('http://api.service.com/absolute/path/subscribe?api_key={key}');

const req = client.request();
req.setEncoding('utf8');

req.on('response', (headers, flags) => {
  console.log(headers);
});

let data = '';
req.on('data', (d) => data += d);
req.on('end', () => {
    console.log('end');
    console.log(data); 
    client.destroy()
});
req.end();

旁注:我是 Node.js 新手,http/2 推送流对我来说也是一个新话题,所以请考虑我是初学者,正在为此苦苦挣扎。

【问题讨论】:

    标签: node.js stream push http2


    【解决方案1】:

    在一些帮助下解决,使用“请求”库: https://www.npmjs.com/package/request

    const request = require("request");
    
    const getPushData = () => {
        let completeResponse = "";
        request
        .get('http://api.service.com/absolute/path/subscribe?api_key={key}')
        .on('response', (response)=>{
            console.log("Response received successfully");
        })
        .on('data', (chunk)=>{
            console.log("Receiving the chunk...");
            console.log(chunk);
            let dataReceived = new Buffer(chunk).toString("utf8");
            console.log(dataReceived);
    
            completeResponse += chunk;        
        })
        .on('error', (err)=>{
            console.log("Something went wrong:");
            console.log(err.message);
        })
        .on("end", ()=>{
            console.log("The complete data received is:");
            console.log(completeResponse);
            let jsonObj = JSON.parse(completeResponse); 
            console.log(jsonObj);
        });
    }
    
    getPushData();
    

    旁注:此脚本的问题在于,如果连接断开,则流不会恢复。

    【讨论】:

    • 不确定这是否是您想要的,但request 不支持 HTTP2。如果您的代码现在可以工作,那一定是因为连接回退到 HTTP 1.1
    猜你喜欢
    • 2018-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-17
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    相关资源
    最近更新 更多