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'
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.
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');
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.
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) }
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With