简体   繁体   English

Express.JS:如何按名称而不是数字设置响应状态?

[英]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.

相关问题 如何在 express.js 资产上设置响应 header - How can I set response header on express.js assets 如何使用Express.js返回304未修改状态? - How do I return 304 Unmodified status with Express.js? 在Express.js服务器中,如何发送从HTTP请求获取的HTML(带有样式和js)作为响应? - In an Express.js server, how can I send an HTML (with style and js) acquired from a HTTP request, as a response? 如何知道传入请求是否在express.js(而不是CSS,JS等)中要求HTML - How to know if incoming requests are asking for HTML in express.js (rather than CSS, JS, etc) 我如何使用node和express.js仅发送json响应中的特定字段? - How can i send only particular field in json response using node and express.js? 如何使用 express.js 在 socket.io 的响应中过度添加自定义标头? - How can I over add custom headers to socket.io ' s response with express.js? 在Express.js中,如何在没有“响应”对象的情况下渲染Jade部分视图? - In Express.js, how can I render a Jade partial-view without a “response” object? 如何在 express.js 中设置使用 response.send () 发送的数据的样式 - How can I style the data sent using response.send () in express.js 如何解决 Express.js 404 状态? - how to solve Express.js 404 status? Express.js - 我无法设置 Content-Type - Express.js - I can't set the Content-Type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM