Skip to content

Commit fbed0d1

Browse files
a0viedoMyles Borins
authored and
Myles Borins
committed
doc: merging behavior of writeHead vs setHeader
PR-URL: #5081 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Roman Reiss <[email protected]>
1 parent b0bb42b commit fbed0d1

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

doc/api/http.markdown

+29
Original file line numberDiff line numberDiff line change
@@ -703,6 +703,20 @@ response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
703703
Attempting to set a header field name or value that contains invalid characters
704704
will result in a [`TypeError`][] being thrown.
705705

706+
When headers have been set with [`response.setHeader()`][], they will be merged with
707+
any headers passed to [`response.writeHead()`][], with the headers passed to
708+
[`response.writeHead()`][] given precedence.
709+
710+
```js
711+
// returns content-type = text/plain
712+
const server = http.createServer((req,res) => {
713+
res.setHeader('Content-Type', 'text/html');
714+
res.setHeader('X-Foo', 'bar');
715+
res.writeHead(200, {'Content-Type': 'text/plain'});
716+
res.end('ok');
717+
});
718+
```
719+
706720
### response.setTimeout(msecs, callback)
707721

708722
* `msecs` {Number}
@@ -804,6 +818,20 @@ be called before [`response.end()`][] is called.
804818
If you call [`response.write()`][] or [`response.end()`][] before calling this,
805819
the implicit/mutable headers will be calculated and call this function for you.
806820

821+
When headers have been set with [`response.setHeader()`][], they will be merged with
822+
any headers passed to [`response.writeHead()`][], with the headers passed to
823+
[`response.writeHead()`][] given precedence.
824+
825+
```js
826+
// returns content-type = text/plain
827+
const server = http.createServer((req,res) => {
828+
res.setHeader('Content-Type', 'text/html');
829+
res.setHeader('X-Foo', 'bar');
830+
res.writeHead(200, {'Content-Type': 'text/plain'});
831+
res.end('ok');
832+
});
833+
```
834+
807835
Note that Content-Length is given in bytes not characters. The above example
808836
works because the string `'hello world'` contains only single byte characters.
809837
If the body contains higher coded characters then `Buffer.byteLength()`
@@ -1162,6 +1190,7 @@ There are a few special headers that should be noted.
11621190
[`net.Socket`]: net.html#net_class_net_socket
11631191
[`request.socket.getPeerCertificate()`]: tls.html#tls_tlssocket_getpeercertificate_detailed
11641192
[`response.end()`]: #http_response_end_data_encoding_callback
1193+
[`response.setHeader()`]: #http_response_setheader_name_value
11651194
[`response.write()`]: #http_response_write_chunk_encoding_callback
11661195
[`response.write(data, encoding)`]: #http_response_write_chunk_encoding_callback
11671196
[`response.writeContinue()`]: #http_response_writecontinue

0 commit comments

Comments
 (0)