NodejsWhat is the difference between setHeader and writeHead? The following article will compare setHeader and writeHead and talk about their differences. I hope it will be helpful to everyone!
Today when I was studying Node
, I discovered setHeader# in
Node/http ## is very similar to writeHead. Both can set the response header. Let’s talk about it in detail!
Parameter
response.setHeader(name, value)复制代码
Return the response object
Function
Set a single attribute for the response header.Note
Example
reponse.setHeader('Content-Type', 'text/html')
reponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript'])
Repeatedly set an attribute
// 返回 content-type = text/html1 reponse.setHeader('Content-Type', 'text/html') reponse.setHeader('Content-Type', 'text/html1')
response.writeHead(statusCode, [statusMessage], [headers])
Return response object
has the same effect as
setHeader
Called before
Because writeHead returns 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);
Use setHeader and writeHead at the same time
// 返回 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'); });
setHeader, and writeHead can only be called once, so when calling, first consider which headers do not change often, and then call
writeHeadIf
setHeader
writeHead merge
If this method is called, and
response has not been called yet .setHeader()
response.getHeader()) on the header does not produce the expected results. If the header needs to be populated incrementally with potential future retrieval and modification, use
response.setHeader() instead.
Summary
setHeader can be called repeatedly, writeHead can only be called once
setHeader and writeHead appear at the same time, setHeader will be merged into writeHead, and writeHead has a high priority
writeHead can set the status code and status information, setHeader cannot be set, only the header can be set
nodejs tutorial
!The above is the detailed content of Briefly compare setHeader and writeHead in Node and talk about the differences.. For more information, please follow other related articles on the PHP Chinese website!