Skip to content

Commit

Permalink
http: enable call chaining with setHeader()
Browse files Browse the repository at this point in the history
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 <luigipinca@gmail.com>
Reviewed-By: Ricky Zhou <0x19951125@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
  • Loading branch information
PoojaDurgad authored and danielleadams committed Dec 7, 2020
1 parent d95ae65 commit 58abdca
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
6 changes: 5 additions & 1 deletion doc/api/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -1595,13 +1595,17 @@ added: v0.4.0

* `name` {string}
* `value` {any}
* Returns: {http.ServerResponse}

Returns the response object.

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

```js
response.setHeader('Content-Type', 'text/html');
Expand Down
1 change: 1 addition & 0 deletions lib/_http_outgoing.js
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,7 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) {
this[kOutHeaders] = headers = ObjectCreate(null);

headers[name.toLowerCase()] = [name, value];
return this;
};


Expand Down
29 changes: 29 additions & 0 deletions test/parallel/test-http-set-header-chain.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use strict';
const common = require('../common');
const http = require('http');
const assert = require('assert');
const expected = {
'__proto__': null,
'testheader1': 'foo',
'testheader2': 'bar',
'testheader3': 'xyz'
};
const server = http.createServer(common.mustCall((req, res) => {
let retval = res.setHeader('testheader1', 'foo');

// Test that the setHeader returns the same response object.
assert.strictEqual(retval, res);

retval = res.setHeader('testheader2', 'bar').setHeader('testheader3', 'xyz');
// Test that chaining works for setHeader.
assert.deepStrictEqual(res.getHeaders(), expected);
res.end('ok');
}));
server.listen(0, () => {
http.get({ port: server.address().port }, common.mustCall((res) => {
res.on('data', () => {});
res.on('end', common.mustCall(() => {
server.close();
}));
}));
});

0 comments on commit 58abdca

Please sign in to comment.