如何在Node.js HTTP2中获取请求体?

问题描述 投票:2回答:1

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

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个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.