Search code examples
javascriptnode.jshttp2

How to get request body in Node.js HTTP2?


I have the following code, but no idea how to get the body from the request:

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)

Solution

  • I think you should consider the stream as a 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 = [];    
        });
    
    });
    

    Also, according to the documentation the third argument of server.on('stream' callback is flags, not body.