diff --git a/lib/context.js b/lib/context.js index 0c94725..058b6a7 100644 --- a/lib/context.js +++ b/lib/context.js @@ -115,8 +115,14 @@ var proto = module.exports = { return; } - // unset all headers, and set those specified - this.res._headers = {}; + // first unset all headers + if (this.res.getHeaderNames) { + this.res.getHeaderNames().forEach(function(name) { this.removeHeader(name) }, this.res); + } else { + this.res._headers = {}; // Node < 8 + } + + // then set those specified this.set(err.headers); // force text/plain diff --git a/lib/response.js b/lib/response.js index e2038c0..21a8b7f 100644 --- a/lib/response.js +++ b/lib/response.js @@ -44,7 +44,9 @@ module.exports = { */ get header() { - return this.res._headers || {}; + return this.res.getHeaders + ? this.res.getHeaders() + : this.res._headers || {}; // Node < 8 }, /** diff --git a/test/context/onerror.js b/test/context/onerror.js index b2a4001..fd5defd 100644 --- a/test/context/onerror.js +++ b/test/context/onerror.js @@ -1,8 +1,10 @@ 'use strict'; +var assert = require('assert'); var request = require('supertest'); var koa = require('../..'); +var context = require('../context'); describe('ctx.onerror(err)', function(){ it('should respond', function(done){ @@ -147,4 +149,21 @@ describe('ctx.onerror(err)', function(){ .expect('Internal Server Error', done); }) }) + + it('should use res.getHeaderNames when available', function(){ + var removed = 0; + var ctx = context(); + + ctx.app.emit = function() {}; + ctx.res = { + getHeaderNames: function() { return ['content-type', 'content-length'] }, + removeHeader: function() { removed++ }, + end: function() {}, + emit: function() {} + }; + + ctx.onerror(new Error('error')); + + assert.equal(removed, 2); + }) }) diff --git a/test/response/header.js b/test/response/header.js index 02820dd..abf839c 100644 --- a/test/response/header.js +++ b/test/response/header.js @@ -10,6 +10,16 @@ describe('res.header', function(){ res.header.should.eql({ 'x-foo': 'bar' }); }) + it('should use res.getHeaders helper when it is available', function(){ + var res = response(null, { + _headers: {}, + getHeaders: function(){ + return { 'x-foo': 'baz' } + } + }); + res.header.should.eql({ 'x-foo': 'baz' }); + }) + describe('when res._headers not present', function (){ it('should return empty object', function (){ var res = response();