How to quickly get started with VUE3.0: Enter learning.
Today when I was learning Node
I found that setHeader and writeHead in Node/http
are very similar. They can both set response headers. Let’s talk about it in detail!
parameters
response.setHeader(name, value)Copy code
http.ServerResponse
returns the response objectand
sets a single attribute for the response header.
Note that
TypeError
to be thrown.Example
response.setHeader('Content-Type', 'text/html')
response. setHeader('Set-Cookie', ['type=ninja', 'language=javascript'])
repeatedly sets an attribute
// returns content-type = text/html1 response.setHeader('Content-Type', 'text/html') response.setHeader('Content-Type', 'text/html1')
parameter
response.writeHead(statusCode, [statusMessage], [headers])
statusCode http status code
statusMessage status message (optional)
headers | attribute object or array (optional)
return http.ServerResponse
return response object
The function
is the same as that setHeader
Note
that multiple properties can be set. setHeader can only set one
and can only be called once.
It must be called before response.end()
Setting the property field name or value containing invalid characters will cause TypeError
to be thrown.
Example
because writeHead returns It is a ServerResponse object, we can make chain calls
const body = 'hello world'; response .writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/plain' }) .end(body);
Content-Length here is in bytes, not characters. Buffer.byteLength() is used to determine the length of the text.
Nodejs will not check whether Content-Length is consistent with the length of the transmitted text.
// Return 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'); });
writeHead
has a higher priority than setHeader
, and writeHead can only be called once, so when calling, first consider which headers do not change often, and then call writeHead
If setHeader
has been called to set the header, then he will pass it to writeHead
merge
If this method is called and response.setHeader()
has not been called), the provided header value will be written directly to the network channel and will not be cached internally. response.getHeader()
) on the header does not produce the expected results. If the header needs to be populated incrementally and potentially retrieved and modified in the future, use response.setHeader()
instead.
setHeader can only set headers one by one, writeHead can set many
setHeaders at once, and can be called repeatedly. writeHead can only be called once, and
setHeader and writeHead appear at the same time. setHeader will be merged into writeHead, and writeHead has a high priority.
writeHead can set status codes and status information. , setHeader cannot be set, only the header can be set