response.writeHead(statusCode[, statusMessage][, headers])


向请求发送响应头。状态码是一个三位数的 HTTP 状态码,例如 404。最后一个参数 headers 是响应头。可选地,可以将人类可读的 statusMessage 作为第二个参数提供。

【Sends a response header to the request. The status code is a 3-digit HTTP status code, like 404. The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.】

headers 可能是一个 Array,其键和值在同一个列表中。它 不是 一个元组列表。因此,偶数索引是键,奇数索引是对应的值。这个数组的格式与 request.rawHeaders 相同。

返回对 ServerResponse 的引用,以便可以进行链式调用。

【Returns a reference to the ServerResponse, so that calls can be chained.】

const body = 'hello world';
response
  .writeHead(200, {
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'text/plain',
  })
  .end(body); 

此方法只能在消息上调用一次,并且必须在调用 response.end() 之前调用。

【This method must only be called once on a message and it must be called before response.end() is called.】

如果在调用此函数之前调用 response.write()response.end(),将会计算隐式/可变头并调用此函数。

【If response.write() or response.end() are called before calling this, the implicit/mutable headers will be calculated and call this function.】

当使用 response.setHeader() 设置了头部时,它们将与传递给 response.writeHead() 的任何头部合并,而传递给 response.writeHead() 的头部优先。

【When headers have been set with response.setHeader(), they will be merged with any headers passed to response.writeHead(), with the headers passed to response.writeHead() given precedence.】

如果调用此方法而 response.setHeader() 尚未被调用,它将直接将提供的头部值写入网络通道,而不会在内部缓存,并且头部上的 response.getHeader() 不会产生预期的结果。如果希望逐步填充头部,并在将来可能进行检索和修改,请改用 response.setHeader()

【If this method is called and response.setHeader() has not been called, it will directly write the supplied header values onto the network channel without caching internally, and the response.getHeader() on the header will not yield the expected result. If progressive population of headers is desired with potential future retrieval and modification, use response.setHeader() instead.】

// Returns content-type = text/plain
const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html');
  res.setHeader('X-Foo', 'bar');
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ok');
}); 

Content-Length 是按字节读取的,而不是按字符。使用 Buffer.byteLength() 来确定正文的字节长度。Node.js 会检查 Content-Length 与已传输正文的长度是否相等。

尝试设置包含无效字符的头字段名称或值将导致抛出 TypeError

【Attempting to set a header field name or value that contains invalid characters will result in a TypeError being thrown.】