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


向请求发送响应头。状态码是一个三位数的 HTTP 状态码,例如 404。最后一个参数 headers 是响应头。

🌐 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.

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

🌐 Returns a reference to the Http2ServerResponse, so that calls can be chained.

为了与 HTTP/1 兼容,可以将可读的 statusMessage 作为第二个参数传入。然而,由于 statusMessage 在 HTTP/2 中没有实际意义,该参数将不会产生任何效果,并且会触发进程警告。

🌐 For compatibility with HTTP/1, a human-readable statusMessage may be passed as the second argument. However, because the statusMessage has no meaning within HTTP/2, the argument will have no effect and a process warning will be emitted.

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

Content-Length 是以字节为单位而不是字符。可以使用 Buffer.byteLength() API 来确定特定编码下的字节数。在发送消息时,Node.js 不会检查 Content-Length 与传输的主体长度是否相等。然而,在接收消息时,当 Content-Length 与实际负载大小不匹配时,Node.js 会自动拒绝该消息。

在调用 response.end() 之前,这个方法最多只能在一条消息上调用一次。

🌐 This method may be called at most one time on a message 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.

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

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

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