response.setHeader(name, value)
name<string>value数字 | 字符串 | 字符串数组- 返回: <http.ServerResponse>
返回响应对象。
【Returns the response object.】
为隐式头设置单个头值。如果该头已存在于待发送的头中,其值将被替换。这里使用字符串数组可以发送具有相同名称的多个头。非字符串值将被原样存储。因此,response.getHeader() 可能返回非字符串值。不过,非字符串值在网络传输时会被转换为字符串。相同的响应对象将返回给调用者,以便实现方法链式调用。
【Sets a single header value for implicit headers. If this header already exists
in the to-be-sent headers, its value will be replaced. Use an array of strings
here to send multiple headers with the same name. Non-string values will be
stored without modification. Therefore, response.getHeader() may return
non-string values. However, the non-string values will be converted to strings
for network transmission. The same response object is returned to the caller,
to enable call chaining.】
response.setHeader('Content-Type', 'text/html'); 或者
【or】
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); 尝试设置包含无效字符的头字段名称或值将导致抛出 TypeError。
【Attempting to set a header field name or value that contains invalid characters
will result in a TypeError being thrown.】
当使用 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 = 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');
}); 如果调用 response.writeHead() 方法,而该方法之前未被调用,它会直接将提供的头部值写入网络通道,而不会在内部缓存,并且头部上的 response.getHeader() 不会产生预期的结果。如果希望逐步填充头部,同时可能进行将来的检索和修改,请使用 response.setHeader() 而不是 response.writeHead()。
【If response.writeHead() method is called and this method 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 of response.writeHead().】