mirror of
https://github.com/nodejs/node.git
synced 2026-10-28 10:15:07 +08:00
http: enable call chaining with setHeader()
Make `response.setHeader` return the response object itself so that multiple header setting can be chained. Fixes: https://github.com/nodejs/node/issues/33148 PR-URL: https://github.com/nodejs/node/pull/35924 Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Ricky Zhou <0x19951125@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com>
This commit is contained in:
1 parent
f34866a61c
commit
dedd0612f0
3 files changed
+35
-1
No files matched your search
+5
-1
@@ -1597,13 +1597,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');
|
||||
|
||||
@@ -570,6 +570,7 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) {
|
||||
this[kOutHeaders] = headers = ObjectCreate(null);
|
||||
|
||||
headers[name.toLowerCase()] = [name, value];
|
||||
return this;
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -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();
|
||||
}));
|
||||
}));
|
||||
});
|
||||
Reference in new issue
Block a user