Skip to content

Commit 58abdca

Browse files
PoojaDurgaddanielleadams
authored andcommitted
http: enable call chaining with setHeader()
Make `response.setHeader` return the response object itself so that multiple header setting can be chained. Fixes: #33148 PR-URL: #35924 Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Ricky Zhou <[email protected]> Reviewed-By: Rich Trott <[email protected]>
1 parent d95ae65 commit 58abdca

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

doc/api/http.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1595,13 +1595,17 @@ added: v0.4.0
15951595

15961596
* `name` {string}
15971597
* `value` {any}
1598+
* Returns: {http.ServerResponse}
1599+
1600+
Returns the response object.
15981601

15991602
Sets a single header value for implicit headers. If this header already exists
16001603
in the to-be-sent headers, its value will be replaced. Use an array of strings
16011604
here to send multiple headers with the same name. Non-string values will be
16021605
stored without modification. Therefore, [`response.getHeader()`][] may return
16031606
non-string values. However, the non-string values will be converted to strings
1604-
for network transmission.
1607+
for network transmission. The same response object is returned to the caller,
1608+
to enable call chaining.
16051609

16061610
```js
16071611
response.setHeader('Content-Type', 'text/html');

lib/_http_outgoing.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,7 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) {
570570
this[kOutHeaders] = headers = ObjectCreate(null);
571571

572572
headers[name.toLowerCase()] = [name, value];
573+
return this;
573574
};
574575

575576

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'use strict';
2+
const common = require('../common');
3+
const http = require('http');
4+
const assert = require('assert');
5+
const expected = {
6+
'__proto__': null,
7+
'testheader1': 'foo',
8+
'testheader2': 'bar',
9+
'testheader3': 'xyz'
10+
};
11+
const server = http.createServer(common.mustCall((req, res) => {
12+
let retval = res.setHeader('testheader1', 'foo');
13+
14+
// Test that the setHeader returns the same response object.
15+
assert.strictEqual(retval, res);
16+
17+
retval = res.setHeader('testheader2', 'bar').setHeader('testheader3', 'xyz');
18+
// Test that chaining works for setHeader.
19+
assert.deepStrictEqual(res.getHeaders(), expected);
20+
res.end('ok');
21+
}));
22+
server.listen(0, () => {
23+
http.get({ port: server.address().port }, common.mustCall((res) => {
24+
res.on('data', () => {});
25+
res.on('end', common.mustCall(() => {
26+
server.close();
27+
}));
28+
}));
29+
});

0 commit comments

Comments
 (0)