【问题标题】:How to get request body in Node.js HTTP2?如何在 Node.js HTTP2 中获取请求正文?
【发布时间】:2019-08-10 02:53:20
【问题描述】:

我有以下代码,但不知道如何从请求中获取正文:

var http2 = require('http2');
var fs = require('fs');

var server = http2.createSecureServer({
  key: fs.readFileSync('localhost-privkey.pem'),
  cert: fs.readFileSync('localhost-cert.pem')
})

server.on('error', function (error) { console.error(error) })

server.on('stream', function (stream, headers, body) {

  var method = headers[':method']
  var path = headers[':path']
  var body = body || ''

  console.log(method, path, body)

  stream.respond({
    'content-type': `text/${type}`,
    ':status': 200
  })

  fs.readFile(file, function (error, file) {
    if (error) file = fs.readFileSync('error.html')
    return stream.end(file)
  })
})

server.listen(3443)

【问题讨论】:

    标签: javascript node.js http2


    【解决方案1】:

    我认为您应该将stream 视为readable stream

    server.on('stream', (stream, headers) => {
        var chunks = [];
    
        stream.on('data', function (chunk) {
            chunks.push(chunk);
        });
    
        stream.on('end', function () {
            // Here is your body
            var body = Buffer.concat(chunks);
    
            // Not sure if useful
            chunks = [];    
        });
    
    });
    

    另外,根据documentationserver.on('stream' 回调的第三个参数是flags,而不是body

    【讨论】:

      猜你喜欢
      • 2021-12-25
      • 2017-02-23
      • 2015-09-09
      • 1970-01-01
      • 2021-02-25
      • 2021-07-22
      • 2021-10-29
      • 2023-03-13
      • 1970-01-01
      相关资源
      最近更新 更多