Skip to content

Commit cec62a5

Browse files
committed
Avoid overriding headers set in onresponse
Currently, overriding a header from the target response in the source response requires doing it in both ondata_response (when receiving the first chunk of data) and in onend_response (for when the response doesn't contain any data), after verifying that res.headersSent is false. That's clumsy at best. By filtering the copied headers with those already present in the source response, it's possible to set them in onresponse once and for all.
1 parent 1fe7f0f commit cec62a5

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

lib/plugins-middleware.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,9 @@ function handleTargetResponse(targetRequest, targetResponse, options, cb) {
388388
Object.keys(targetResponse.headers).forEach(function(header) {
389389
// skip setting the 'connection: keep-alive' header
390390
// setting it causes gateway to not accept any more connections
391-
if (header !== 'connection') {
391+
// Headers that have been set in onresponse are also skipped to let the plugins override those from the
392+
// target response.
393+
if (header !== 'connection' && !sourceResponse.hasHeader(header)) {
392394
sourceResponse.setHeader(header, targetResponse.headers[header]);
393395
}
394396
});

tests/plugin-lifecycle-tests.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,27 @@ describe('test lifecycle events', function() {
301301
});
302302
});
303303
});
304+
305+
it('should keep the header set on the source response', function(done) {
306+
this.timeout(20000);
307+
const testPlugin = TestPlugin((type, data, cb) => cb());
308+
const handler = testPlugin.init();
309+
handler.onresponse = (sourceReq, sourceRes, targetRes, data, next) => {
310+
sourceRes.setHeader('content-type', 'application/octet-stream');
311+
sourceRes.setHeader('original-content-type', targetRes.headers['content-type']);
312+
next();
313+
};
314+
gateway.addPlugin('test', () => handler);
315+
316+
gateway.start((err) => {
317+
assert(!err, err);
318+
request({ method: 'GET', url: 'http://localhost:' + gatewayPort + '/v1/echo/get' }, (err, r) => {
319+
assert.equal(r.headers['content-type'], 'application/octet-stream');
320+
assert.equal(r.headers['original-content-type'], 'application/json');
321+
done();
322+
});
323+
});
324+
});
304325
});
305326

306327
function _findHeaders(headers, expectedHeaders) {

0 commit comments

Comments
 (0)