HTTP响应代码不是魔术数字;它们是规范。描述性文本只是一种有用的提醒,但协议本身依赖于这些状态码,而核心状态码非常值得学习。有两个想法。您肯定可以在文件顶部创建一个常量并执行此操作:
var REQUEST_ENTITY_TOO_LARGE = 413;
response.status(REQUEST_ENTITY_TOO_LARGE);
然而,大多数REST API只实现以下响应:
200 - OK
201 - Created
302 - Found
303 - See Other
304 - Not Modified
400 - Bad Request
401 - Unauthorized
403 - Forbidden
404 - Not Found
500 - Internal Server Error
最后,如果有帮助的话,我将分享我们呈现自定义错误页面的代码:
module.exports = function(app) {
app.use(function(req, res) {
res.status(404);
if (req.accepts('html')) {
res.render('error/404', { title:'404: Page not found', error: '404: Page not found', url: req.url });
return;
}
if (req.accepts('json')) {
res.send({ title: '404: Page not found', error: '404: Page not found', url: req.url });
}
});
app.use( function(err, req, res, next) {
var statusCode = err.status || 500;
var statusText = '';
var errorDetail = (process.env.NODE_ENV === 'production') ? 'Sorry about this error' : err.stack;
switch (statusCode) {
case 400:
statusText = 'Bad Request';
break;
case 401:
statusText = 'Unauthorized';
break;
case 403:
statusText = 'Forbidden';
break;
case 500:
statusText = 'Internal Server Error';
break;
}
res.status(statusCode);
if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
console.log(errorDetail);
}
if (req.accepts('html')) {
res.render('error/500', { title: statusCode + ': ' + statusText, error: errorDetail, url: req.url });
return;
}
if (req.accepts('json')) {
res.send({ title: statusCode + ': ' + statusText, error: errorDetail, url: req.url });
}
});
};