【问题标题】:How to make HTTP/2 request with body payload?如何使用正文有效负载发出 HTTP/2 请求?
【发布时间】:2019-02-01 14:23:30
【问题描述】:

我希望打开一个 HTTP/2 流并使用该流发出多个 HTTP/2 POST 请求。每个 POST 请求都有自己的正文负载。

我目前有下面的代码,它适用于不需要有效负载的请求,但我不确定如何为需要有效负载的请求自定义它。

我已经阅读了 RFC 7540 和几乎所有关于 SO 的相关文章,但我仍然发现很难使用有效负载主体编写 HTTP/2 的工作代码

例如:

  • 是使用 stream.write 推荐的方式来发送 DATA 帧,还是应该使用 http2 提供的内置函数?
  • 我是以明文形式传递参数,而 http2 协议负责二进制编码,还是我自己编码?
  • 我应该如何修改以下代码以发送有效负载正文?

.

const http2 = require('http2')
const connection = http2.connect('https://www.example.com:443')

const stream = connection.request({
  ':authority':'www.example.com',
  ':scheme':'https',
  ':method': 'POST',
  ':path': '/custom/path',
}, { endStream: false })

stream.setEncoding('utf8')

stream.on('response', (headers) => {
  console.log('RESPONSE', headers)
  stream.on('data', (data) => console.log('DATA', data))
  stream.on('end', () => console.log('END'))
})

stream.write(Buffer.from('POST-request-payload-body-here?'))

【问题讨论】:

  • @BarryPollard 该线程中的问题类似,但没有解释如何保持连接打开;发送 .write() 后跟 .end() 会立即关闭连接,而在这里我希望保持连接持久打开
  • 流应该被关闭,但您是否尝试在同一连接上发出另一个请求?请注意,如果在设定的时间内未收到其他请求,大多数服务器将超时并关闭整个连接。

标签: node.js http2


【解决方案1】:
  • 您需要做的第一件事是将正文数据转换为缓冲区

    var buffer = new Buffer(JSON.stringify(body));

  • 您需要使用 Content-Type 和 Content-Length 键更新 connection.request 对象。注意 Content-Length 是缓冲区的长度
   const stream = connection.request({
             ':authority':'www.example.com',
             ':scheme':'https',
             ':method': 'POST',
             ':path': '/custom/path',
             'Content-Type': 'application/json',
             'Content-Length': buffer.length
   }, { endStream: false })

  • 最后你需要通过将正文数据转换成字符串来发送请求

   stream.end(JSON.stringify(body));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 1970-01-01
    • 2021-12-29
    • 2013-06-29
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    相关资源
    最近更新 更多