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


向请求发送响应头。状态码是 3 位的 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 和正在传输的正文的长度是否相等。但是,在接收消息时,Node.js 会在 Content-Length 与实际负载大小不匹配时自动拒绝消息。

¥Content-Length is given in bytes not characters. The Buffer.byteLength() API may be used to determine the number of bytes in a given encoding. On outbound messages, Node.js does not check if Content-Length and the length of the body being transmitted are equal or not. However, when receiving messages, Node.js will automatically reject messages when the Content-Length does not match the actual payload size.

在调用 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.