better 404 handling

master
Jonathan Ong 2013-12-29 22:26:19 -08:00
parent 7ee4f43dc0
commit b7b1c0fd44
3 changed files with 11 additions and 31 deletions

View File

@ -180,7 +180,6 @@ app.onerror = function(err){
*/
function *respond(next){
this.status = 200;
if (this.app.poweredBy) this.set('X-Powered-By', 'koa');
yield *next;
@ -189,13 +188,9 @@ function *respond(next){
if (res.headersSent || !res.socket.writable) return;
var body = this.body;
var status = this.status = this.status || 404;
var head = 'HEAD' == this.method;
var noContent = ~[204, 205, 304].indexOf(this.status);
// 404
if (null == body && 200 == this.status) {
this.status = 404;
}
var noContent = ~[204, 205, 304].indexOf(status);
// ignore body
if (noContent) return res.end();
@ -203,7 +198,7 @@ function *respond(next){
// status body
if (null == body) {
this.type = 'text';
body = http.STATUS_CODES[this.status];
body = http.STATUS_CODES[status];
}
// Buffer body

View File

@ -49,7 +49,7 @@ module.exports = {
*/
get statusString() {
return http.STATUS_CODES[this.status];
return http.STATUS_CODES[this.status || 404];
},
/**
@ -60,7 +60,7 @@ module.exports = {
*/
get status() {
return this.res.statusCode;
return this._status;
},
/**
@ -77,9 +77,8 @@ module.exports = {
val = n;
}
this.res.statusCode = val;
var noContent = 304 == this.status || 204 == this.status;
var status = this._status = this.res.statusCode = val;
var noContent = 304 == status || 204 == status;
if (noContent && this.body) this.body = null;
},
@ -114,6 +113,9 @@ module.exports = {
return;
}
// set the status
this.status = this.status || 200;
// set the content-type only if not yet set
var setType = !this.header['content-type'];

View File

@ -119,7 +119,7 @@ describe('app.respond', function(){
var app = koa();
app.use(function *(){
this.status = 200;
})
var server = app.listen();
@ -229,23 +229,6 @@ describe('app.respond', function(){
})
})
describe('with status=200', function(){
it('should respond with a 404', function(done){
var app = koa();
app.use(function *(){
this.status = 200;
})
var server = app.listen();
request(server)
.get('/')
.expect(404)
.expect('Not Found', done);
})
})
describe('with status=204', function(){
it('should respond without a body', function(done){
var app = koa();