response: don't access res._headers directly when helpers exist

res._headers is considered internal to node itself. Its value will
change in a backwards incompatible way in the future node releases.

Use the documented helper functions instead when they are available.
This commit is contained in:
Ilkka Oksanen 2017-02-21 07:52:57 +01:00 committed by jongleberry
parent 0b9c8b8078
commit 91c403a541
4 changed files with 40 additions and 3 deletions

View file

@ -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

View file

@ -44,7 +44,9 @@ module.exports = {
*/
get header() {
return this.res._headers || {};
return this.res.getHeaders
? this.res.getHeaders()
: this.res._headers || {}; // Node < 8
},
/**

View file

@ -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);
})
})

View file

@ -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();