Usage in Deno
import { ServerResponse } from "node:http";
ServerResponse.prototype.writeHead(): this
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
may be an Array
where the keys and values are in the same list.
It is not a list of tuples. So, the even-numbered offsets are key values,
and the odd-numbered offsets are the associated values. The array is in the same
format as request.rawHeaders
.
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);
This method must only be called once on a message and it must
be called before response.end()
is called.
If response.write()
or response.end()
are called before calling
this, the implicit/mutable headers will be calculated and call this function.
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.
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
is read in bytes, not characters. Use Buffer.byteLength()
to determine the length of the body in bytes. Node.js
will check whether Content-Length
and the length of the body which has
been transmitted are equal or not.
Attempting to set a header field name or value that contains invalid characters
will result in a [Error
][] being thrown.
headers: OutgoingHttpHeaders | OutgoingHttpHeader[]
this
ServerResponse.prototype.writeHead(statusCode: number,headers?: OutgoingHttpHeaders | OutgoingHttpHeader[],): this
headers: OutgoingHttpHeaders | OutgoingHttpHeader[]
this