diff --git a/lib/plugins-middleware.js b/lib/plugins-middleware.js index d0848d4..5dbccd5 100644 --- a/lib/plugins-middleware.js +++ b/lib/plugins-middleware.js @@ -362,7 +362,9 @@ function handleTargetResponse(targetRequest, targetResponse, options, cb) { Object.keys(targetResponse.headers).forEach(function(header) { // skip setting the 'connection: keep-alive' header // setting it causes gateway to not accept any more connections - if (header !== 'connection') { + // Headers that have been set in onresponse are also skipped to let the plugins override those from the + // target response. + if (header !== 'connection' && !sourceResponse.hasHeader(header)) { sourceResponse.setHeader(header, targetResponse.headers[header]); } }); diff --git a/tests/plugin-lifecycle-tests.js b/tests/plugin-lifecycle-tests.js index a47c353..1955c73 100644 --- a/tests/plugin-lifecycle-tests.js +++ b/tests/plugin-lifecycle-tests.js @@ -301,6 +301,27 @@ describe('test lifecycle events', function() { }); }); }); + + it('should keep the header set on the source response', function(done) { + this.timeout(20000); + const testPlugin = TestPlugin((type, data, cb) => cb()); + const handler = testPlugin.init(); + handler.onresponse = (sourceReq, sourceRes, targetRes, data, next) => { + sourceRes.setHeader('content-type', 'application/octet-stream'); + sourceRes.setHeader('original-content-type', targetRes.headers['content-type']); + next(); + }; + gateway.addPlugin('test', () => handler); + + gateway.start((err) => { + assert(!err, err); + request({ method: 'GET', url: 'http://localhost:' + gatewayPort + '/v1/echo/get' }, (err, r) => { + assert.equal(r.headers['content-type'], 'application/octet-stream'); + assert.equal(r.headers['original-content-type'], 'application/json'); + done(); + }); + }); + }); }); function _findHeaders(headers, expectedHeaders) {