response.setHeader(name, value)
name
<string>value
<string> | <string[]>
为隐式标头设置单个标头值。 如果该标头已经存在于待发送的标头中,则其值将被替换。 在此处使用字符串数组发送具有相同名称的多个标头。
response.setHeader('Content-Type', 'text/html; charset=utf-8');
或者
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
尝试设置包含无效字符的标头字段名称或值将导致抛出 TypeError
。
当标头已使用 response.setHeader()
设置时,则它们将与任何传给 response.writeHead()
的标头合并,其中传给 response.writeHead()
的标头优先。
// 返回 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');
});
name
<string>value
<string> | <string[]>
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.
response.setHeader('Content-Type', 'text/html; charset=utf-8');
or
response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
Attempting to set a header field name or value that contains invalid characters
will result in a TypeError
being thrown.
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');
});