Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.JS: how can I set response status by name rather than number?

OK, everyone knows 200 is OK and 404 is not found. 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:

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.

How can I specify a response status by name in Express JS?

Edit: thanks @Akshat for pointing out 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'
like image 308
mikemaccana Avatar asked Aug 19 '13 10:08

mikemaccana


People also ask

How do you set a status code in response?

To set a different HTTP status code from your Servlet, call the following method on the HttpServletResponse object passed in to your server: res. setStatus(nnn); where nnn is a valid HTTP status code.

Which are the valid method that can be called on the response object in Express?

Response Location method This method is used to set the response location HTTP header field based on the specified path parameter. Examples: res. location('http://xyz.com');

How do I send a status code in response Nodejs?

The res. sendStatus() function is used to set the response HTTP status code to statusCode and send its string representation as the response body. Parameter: The statusCode parameter describes the HTTP status code.


1 Answers

There's a Node module just for this purpose: 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) }
);
like image 130
stone Avatar answered Oct 13 '22 21:10

stone