diff --git a/doc/api/http.md b/doc/api/http.md index 8e7056114bee8f..e5e4609dbcf03c 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -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'); diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 1ff2de2aab868c..8fb64ab82efceb 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -570,6 +570,7 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) { this[kOutHeaders] = headers = ObjectCreate(null); headers[name.toLowerCase()] = [name, value]; + return this; }; diff --git a/test/parallel/test-http-set-header-chain.js b/test/parallel/test-http-set-header-chain.js new file mode 100644 index 00000000000000..aa9519129a9123 --- /dev/null +++ b/test/parallel/test-http-set-header-chain.js @@ -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(); + })); + })); +});