nodejs/node

http server respond with inappropriate default headers for `HEAD` method

Open

#28,438 创建于 2019年6月26日

在 GitHub 查看
 (3 评论) (0 反应) (0 负责人)JavaScript (117,218 star) (35,535 fork)batch import
help wantedhttp

描述

  • Version: >= 10.x
  • Platform: any
  • Subsystem: http

To implement a HTTP keep alive mechanism, I use the http.Agent({ keepAlive: true }) and http.request({ agent, method, host, port }).

Everything is ok when the method is GET or TRACE and others, the agent reuse the TCP connection as I expect.

But when changing the method to HEAD, the agent close the connection when server responded.

From the response header, the only different is that: for HEAD method, there isn't a Content-Length: 0 or Transfer-Encoding: chunked in the default header (but GET has by default), so the HTTP parser think this connection should not be kept alive.

But from the RFC, we can infer that if keep-alive was enabled, either Content-Length: 0 or Transfer-Encoding: chunked should be setted in response header, I think this should be a default behavior.

# server
const http = require("http")

const server = http.createServer((req, res) => {
  // res.setHeader("Content-Length", 0)
  // res.setHeader("Transfer-Encoding", "chunked")
  res.end()
})

server.keepAliveTimeout = 0
server.listen(2333, "x.x.x.x")
# client
const http = require("http")

const agent = new http.Agent({
  keepAlive: true,
})

request = () => {
  const req = http.request({
    agent,
    host: "x.x.x.x",
    port: 2333,
    method: 'HEAD',
  })

  req.end()
}

request()

贡献者指南