HTTP 响应代码不是幻数;他们是规范。描述性文字只是一个有用的提醒,但协议本身依赖于那些状态码,核心的非常值得学习。两个想法。您当然可以在文件顶部创建一个常量并执行以下操作:
var REQUEST_ENTITY_TOO_LARGE = 413;
response.status(REQUEST_ENTITY_TOO_LARGE);
但是,大多数 REST API 只实现以下响应:
200 - OK
201 - Created # Response to successful POST or PUT
302 - Found # Temporary redirect such as to /login
303 - See Other # Redirect back to page after successful login
304 - Not Modified
400 - Bad Request
401 - Unauthorized # Not logged in
403 - Forbidden # Accessing another user's resource
404 - Not Found
500 - Internal Server Error
最后,如果有帮助,我将分享我们用于呈现自定义错误页面的代码:
module.exports = function(app) {
app.use(function(req, res) {
// curl https://localhost:4000/notfound -vk
// curl https://localhost:4000/notfound -vkH "Accept: application/json"
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) {
// curl https://localhost:4000/error/403 -vk
// curl https://localhost:4000/error/403 -vkH "Accept: application/json"
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 });
}
});
};