[英]Express.JS: how can I set response status by name rather than number?
OK, everyone knows 200 is OK and 404 is not found. 好的,每个人都知道200没关系,找不到404。 But I for things like permanent vs temporary redirect, or payment required, or other more exotic HTTP error codes, it might be better to do something like: 但是对于永久与临时重定向或需要付款或其他更奇特的HTTP错误代码之类的东西,最好做以下事情:
response.status('REQUEST_ENTITY_TOO_LARGE');
Rather than just use a magic number which is generally considered bad practice. 而不是仅仅使用一般被认为是不好的魔术数字。 I could, of course, have 413:'REQUEST_ENTITY_TOO_LARGE' in some object, but Express already has a copy of the status code -> name mappings and I'd rather not duplicate that. 当然,我可以在某个对象中有413:'REQUEST_ENTITY_TOO_LARGE',但是Express已经有了状态代码的副本 - >名称映射,我宁愿不重复它。
How can I specify a response status by name in Express JS? 如何在Express JS中按名称指定响应状态?
Edit : thanks @Akshat for pointing out http.STATUS_CODES. 编辑 :感谢@Akshat指出http.STATUS_CODES。 Elaborating on his answer, since the values are themselves unique, one can run: 阐述他的答案,因为价值观本身是独一无二的,人们可以运行:
var statusCodeByName = {};
for ( var number in http.STATUS_CODES ) {
statusCodeByName[http.STATUS_CODES[number]] = number
}
Which allows one to: 这允许一个人:
> statusCodeByName['Request Entity Too Large']
'413'
There's a Node module just for this purpose: http-status-codes. 有一个Node模块就是为了这个目的:http-status-codes。
https://www.npmjs.org/package/http-status-codes https://www.npmjs.org/package/http-status-codes
Here's what the documentation says: 这是文档说的内容:
Installation 安装
npm install http-status-codes
Usage 用法
var HttpStatus = require('http-status-codes');
response.send(HttpStatus.OK);
response.send(
HttpStatus.INTERNAL_SERVER_ERROR,
{ error: HttpStatus.getStatusText(HttpStatus.INTERNAL_SERVER_ERROR) }
);
HTTP response codes are not magic numbers; HTTP响应代码不是幻数; they are the spec. 他们是规范。 The descriptive text is just a helpful reminder, but the protocol itself relies on those status codes, and the core ones are very worth learning. 描述性文本只是一个有用的提示,但协议本身依赖于这些状态代码,核心代码非常值得学习。 Two thoughts. 两个想法。 You can certainly create a constant at the top of your file and do this: 您当然可以在文件顶部创建一个常量并执行以下操作:
var REQUEST_ENTITY_TOO_LARGE = 413;
response.status(REQUEST_ENTITY_TOO_LARGE);
However, most REST APIs just implement the following responses: 但是,大多数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
Finally, in case it's helpful, I'll share our code for rendering custom error pages: 最后,如果它有用,我将分享我们用于呈现自定义错误页面的代码:
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 });
}
});
};
This is not possible unless you are willing to change the source code yourself. 除非您愿意自己更改源代码,否则这是不可能的。 Take a look at the implementation of res.send
看一下res.send
的实现
If you provide a string as an argument it just interprets it as html and sends the response as 200. 如果您提供一个字符串作为参数,它只是将其解释为html并将响应发送为200。
I think the reason express uses numbers for HTTP status codes is because node itself uses numbers as object keys for http.STATUS_CODES 我认为express的原因是使用HTTP状态代码的数字是因为节点本身使用数字作为http.STATUS_CODES的对象键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.