Giter Club home page Giter Club logo

http-status-codes's Introduction

http-status-codes

Constants enumerating the HTTP status codes. Based on the Java Apache HttpStatus API.

All status codes defined in the following RFCs are supported:

  • RFC1945 (HTTP/1.0)
  • RFC2616 (HTTP/1.1)
  • RFC7231 (HTTP/1.1: Semantics and Content)
  • RFC2518 (WebDAV)
  • RFC6585 (Additional HTTP Status Codes)
  • RFC7538 (Permanent Redirect)
  • RFC8297 (An HTTP Status Code for Indicating Hints)

TypeScript or JavaScript. Completely library agnostic. No dependencies.

Installation

npm install http-status-codes --save

Usage (express 4.x)

import {
	ReasonPhrases,
	StatusCodes,
	getReasonPhrase,
	getStatusCode,
} from 'http-status-codes';

response
	.status(StatusCodes.OK)
	.send(ReasonPhrases.OK);

response
	.status(StatusCodes.INTERNAL_SERVER_ERROR)
	.send({
		error: getReasonPhrase(StatusCodes.INTERNAL_SERVER_ERROR)
	});

response
	.status(getStatusCode('Internal Server Error'))
	.send({
		error: 'Internal Server Error'
	});

Codes

Code Constant Reason Phrase
100 CONTINUE Continue
101 SWITCHING_PROTOCOLS Switching Protocols
102 PROCESSING Processing
103 EARLY_HINTS Early Hints
200 OK OK
201 CREATED Created
202 ACCEPTED Accepted
203 NON_AUTHORITATIVE_INFORMATION Non Authoritative Information
204 NO_CONTENT No Content
205 RESET_CONTENT Reset Content
206 PARTIAL_CONTENT Partial Content
207 MULTI_STATUS Multi-Status
300 MULTIPLE_CHOICES Multiple Choices
301 MOVED_PERMANENTLY Moved Permanently
302 MOVED_TEMPORARILY Moved Temporarily
303 SEE_OTHER See Other
304 NOT_MODIFIED Not Modified
305 USE_PROXY Use Proxy
307 TEMPORARY_REDIRECT Temporary Redirect
308 PERMANENT_REDIRECT Permanent Redirect
400 BAD_REQUEST Bad Request
401 UNAUTHORIZED Unauthorized
402 PAYMENT_REQUIRED Payment Required
403 FORBIDDEN Forbidden
404 NOT_FOUND Not Found
405 METHOD_NOT_ALLOWED Method Not Allowed
406 NOT_ACCEPTABLE Not Acceptable
407 PROXY_AUTHENTICATION_REQUIRED Proxy Authentication Required
408 REQUEST_TIMEOUT Request Timeout
409 CONFLICT Conflict
410 GONE Gone
411 LENGTH_REQUIRED Length Required
412 PRECONDITION_FAILED Precondition Failed
413 REQUEST_TOO_LONG Request Entity Too Large
414 REQUEST_URI_TOO_LONG Request-URI Too Long
415 UNSUPPORTED_MEDIA_TYPE Unsupported Media Type
416 REQUESTED_RANGE_NOT_SATISFIABLE Requested Range Not Satisfiable
417 EXPECTATION_FAILED Expectation Failed
418 IM_A_TEAPOT I'm a teapot
419 INSUFFICIENT_SPACE_ON_RESOURCE Insufficient Space on Resource
420 METHOD_FAILURE Method Failure
421 MISDIRECTED_REQUEST Misdirected Request
422 UNPROCESSABLE_ENTITY Unprocessable Entity
423 LOCKED Locked
424 FAILED_DEPENDENCY Failed Dependency
426 UPGRADE_REQUIRED Upgrade Required
428 PRECONDITION_REQUIRED Precondition Required
429 TOO_MANY_REQUESTS Too Many Requests
431 REQUEST_HEADER_FIELDS_TOO_LARGE Request Header Fields Too Large
451 UNAVAILABLE_FOR_LEGAL_REASONS Unavailable For Legal Reasons
500 INTERNAL_SERVER_ERROR Internal Server Error
501 NOT_IMPLEMENTED Not Implemented
502 BAD_GATEWAY Bad Gateway
503 SERVICE_UNAVAILABLE Service Unavailable
504 GATEWAY_TIMEOUT Gateway Timeout
505 HTTP_VERSION_NOT_SUPPORTED HTTP Version Not Supported
507 INSUFFICIENT_STORAGE Insufficient Storage
511 NETWORK_AUTHENTICATION_REQUIRED Network Authentication Required

Migrating from v1.x.x

http-status-codes v2 is mostly backwards compatible with v1. There is a single breaking change and two recommended changes.

[Breaking Change] 'Server Error'

The reason phrase for the status code 500 has been changed from "Server Error" to "Internal Server Error". This is the correct phrase according to RFC7231. If you are migrating from v1, and have code that relies on the result of getStatusText(500) or getReasonPhrase('Server Error'), then this could affect you.

[Non-breaking change] getStatusText renamed getReasonPhrase

The function getStatusText has been renamed to getReasonPhrase. The old function is still available, but may be deprecated in a future version. To fix this simply rename instances of getStatusText() to getReasonPhrase(). The function is otherwise the same as it was before.

[Non-breaking change] StatusCodes

In http-status-codes v1, Status Codes were exported directly from the top-level module. i.e. HttpStatus.OK. In v2 all Status Codes live under an object called StatusCodes. i.e. HttpStatus.StatusCodes.OK. We made this change to cater to TypeScript users who prefer a dedicated value with an enum type. The previous values are still exported, but we won't continue to update them. Please migrate if you're using the old-style imports.

Proposing a new status code

If you'd like to propose a new status code, feel free to update "codes.json" with the necessary information and open a pull request. There is no need to modify source code or even this README. This is done automatically by npm run update-codes.

In general, we try to include only codes that have an official RFC and have been approved, however exceptions can be made if the code is already in widespread use in the wild.

Steps to build and publish

npm run update-codes
npm run test
npm run build
npm version [major | minor | patch]
npm publish

After releasing, please add release notes via GitHub Releases.

http-status-codes's People

Contributors

alessandrojcm avatar angellee177 avatar bmass02 avatar ffflorian avatar jameelkhan9 avatar mesaugat avatar msieurtoph avatar o0ignition0o avatar prettymuchbryce avatar sebdeckers avatar seiyria avatar tlhunter avatar zertosh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

http-status-codes's Issues

Reorder of the status codes enums exported

I find my team looking through the enums for the correct status code to use. Would be really useful to have the ts file ordered and comment blocks inserted outlining http code groups 100, 200, 300, etc.

I am happy to have a look at contributing this.

Error code instead 'text code'?

I like it very much but I have one problem with this :) For response I'm using status code (with is exactly what I need currently in your solution, e.g.: Http.OK) and error code with is missing here. Error code is exactly the name of the code. So in case 200 this is OK, in case 404 the error code is NOT_FOUND. So this is exactly what you named using exports :)

Could you add method getErrorCode which will return the string name of it? E.g Http.getErrorCode(Http.OK) // 'OK'

:)

Codes table order

Just a suggestion, probably table in README should be sorted by code number, currently it's pretty hard to find right spelled property name name by code number

Audit vulnerabilities detected in the httpstatuscodes project on Tag: v2.1.4

Issue: We detected vulnerable dependencies in your project by using the command “npm audit”:

npm audit report

glob-parent <5.1.2
Severity: moderate
Regular expression denial of service - https://npmjs.com/advisories/1751
fix available via npm audit fix
node_modules/glob-parent

hosted-git-info <2.8.9 || >=3.0.0 <3.0.8
Severity: moderate
Regular Expression Denial of Service - https://npmjs.com/advisories/1677
fix available via npm audit fix
node_modules/hosted-git-info

lodash <4.17.21
Severity: high
Command Injection - https://npmjs.com/advisories/1673
fix available via npm audit fix
node_modules/lodash

ws 5.0.0 - 5.2.2 || 6.0.0 - 6.2.1 || 7.0.0 - 7.4.5
Severity: moderate
Regular Expression Denial of Service - https://npmjs.com/advisories/1748
fix available via npm audit fix
node_modules/ws

y18n <3.2.2||=4.0.0||>=5.0.0 <5.0.5
Severity: high
Prototype Pollution - https://npmjs.com/advisories/1654
fix available via npm audit fix
node_modules/y18n

5 vulnerabilities (3 moderate, 2 high)

To address all issues, run:
npm audit fix

Questions: We are conducting a research study on vulnerable dependencies in open-source JS projects. We are curious:

  1. Will you fix the vulnerabilities mentioned above? (Yes/No), and why?:
  2. Do you have any additional comments? (If so, please write it down):

For any publication or research report based on this study, we will share all responses from developers in an anonymous way. Both your projects and personal information will be kept confidential.

Description: Many popular NPM packages have been found vulnerable and may carry significant risks [1]. Developers are recommended to monitor and avoid the vulnerable versions of the library. The vulnerabilities have been identified and reported by other developers, and their descriptions are available in the npm registry [2].

Steps to reproduce:

  • Go to the root folder of the project where the package.json file located
  • Execute “npm audit”
  • Look at the list of vulnerabilities reported

Suggested Solution: Npm has introduced the “npm audit fix” command to fix the vulnerabilities. Execute the command to apply remediation to the dependency tree.

References:
2019. 10 npm Security Best Practices. https://snyk.io/blog/ten-npm-security-best-practices/.
2021. npm-audit. https://docs.npmjs.com/cli/v7/commands/npm-audit.

Rollup: `this` has been rewritten to `undefined`

Rollup was giving me this warning for http-status-codes/build/es/index.js:

bundles src/frontend/main.ts → public/build/bundle.js...
LiveReload enabled
(!) `this` has been rewritten to `undefined`
https://rollupjs.org/guide/en/#error-this-is-undefined
node_modules/http-status-codes/build/es/index.js
1: var __assign = (this && this.__assign) || function () {
                   ^
2:     __assign = Object.assign || function(t) {
3:         for (var s, i = 1, n = arguments.length; i < n; i++) {
...and 1 other occurrence

To eliminate it, I added the following line to my rollup.config.js:

export default {
    // ...
    context: {}, // needed for loading http-status-codes
    // ...
}

But ideally, the module shouldn't be referencing this from the top level.

Code completion removed by improved minification

My IDE does no longer offer code completion for the HTTP status code identifiers, only getStatusText() is suggested. For example:

HttpStatus = require('http-status-codes');

response.status(HttpStatus.    <== code completion only showing 'getStatusText()'

This makes me sad, as I have to look up the code identifiers again and have to type more (without typos). No doubt is the 'improve minification' commit an improvement, however it's also a regression.

My preference is code completion over minification but perhaps there is a win-win?

Make ReasonPhrases compatible with codes as keys.

Currently, we can use StatusCodes similar to a typescript enum like so:

console.log(StatusCodes.GONE); //411
console.log(StatusCodes[411]); //"Gone"

but this does not work with ReasonPhrases:

console.log(ReasonPhrases.GONE); //"Gone"
console.log(ReasonPhrases[411]); //undefined

We should be able to use ReasonPhrases[code]

Could we have a method to go from status text to status code?

For instance, I need to be able to pass in the text 'IM_A_TEAPOT' and get out 418.

Currently 'getStatusText' does the opposite (pass in 418 and get IM_A_TEAPOT out), and I can do this (hacky) in the meantime:

import codes from 'http-status-codes'

console.log(codes['IM_A_TEAPOT'])

But this doesn't seem ideal.

not working in react-native (__dirname not defined)

I assume this is a problem with the typescript transpiration process which adds the following block of code to the top of cjs/index.js. When this is used in a react-native environment it uses that file and then fails because __dirname is not defined. I'm not sure what the fix is this but is a big problem for me and I have to keep using v1 because of it.

module.exports =
/******/ (function(modules, runtime) { // webpackBootstrap
/******/ 	"use strict";
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		var threw = true;
/******/ 		try {
/******/ 			modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ 			threw = false;
/******/ 		} finally {
/******/ 			if(threw) delete installedModules[moduleId];
/******/ 		}
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	__webpack_require__.ab = __dirname + "/";
/******/
/******/ 	// the startup function
/******/ 	function startup() {
/******/ 		// Load entry module and return exports
/******/ 		return __webpack_require__(527);
/******/ 	};
/******/ 	// initialize runtime
/******/ 	runtime(__webpack_require__);
/******/
/******/ 	// run startup
/******/ 	return startup();
/******/ })
/************************************************************************/
/******/ ({

/***/ 527:
/***/ (function(__unusedmodule, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);

Built types importing from codes file not in build folder

Version 2.1.0:

The build output of this package contains import { StatusCodes, ReasonPhrases } from './codes'; in index.d.ts but the build.sh moves the content of codes.d.ts into index.d.ts, so there's no codes.ts/codes.d.ts in the build folder to import from, and for some reason that import isn't removed (unlike the const exports)

This breaks our typescript build. Would it break anything else if you just moved the codes.d.ts file into the build directory as well as the index.d.ts and didn't concatenate them?

$ tsc --project tsconfig.json --declaration --outDir ./dist
node_modules/http-status-codes/build/index.d.ts:1:44 - error TS2307: Cannot find module './codes' or its corresponding type declarations.

1 import { StatusCodes, ReasonPhrases } from './codes';
                                             ~~~~~~~~~


Found 1 error.

Add non-throwing variants

I was very surprised to discover that getReasonPhrase throws an exception when given an HTTP status code that the library does not know about.

Could we add non-throwing variants of getReasonPhrase and getStatusCode that return undefined instead of throwing an exception?

Having to catch the exception just to handle these cases gracefully is not very ergonomic.

I would be willing to open a PR for this if it would be accepted.

GitHub Releases

Would it be possible to use GitHub Releases as well as NPM? It would help to triage changes between versions.

Add description to status codes

Hello there,
Would a brief description of each status codes be helpful?
I am thinking something like this

getDescription(StatusCodes.NOT_FOUND)
// output: The server can not find requested resource. In the browser...

can't install on win32 because dependency on inotify

Hi, when i try to install http-status-codes into my project, got this error:
npm ERR! code EBADPLATFORM
npm ERR! notsup Unsupported platform for [email protected]: wanted {"os":"linux","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm ERR! notsup Valid OS: linux
npm ERR! notsup Valid Arch: any
npm ERR! notsup Actual OS: win32
npm ERR! notsup Actual Arch: x64

Seems its dependency [email protected] couldn't be installed. Can you add a dependency that works for win32? thanks.

Proposal: Move ./lib/httpstatus.js to ./index.js

To further simplify this already simple module, ./lib/httpstatus.js could be move to ./index.js, and the main entry in package.json as well as lib/ directory could be removed entirely. There's a sort of elegance to a module without directories ;).

Thoughts?

Optional Addition of Test Coverage for Consistency

I was thinking about this because on an internal project, we have lightweight test coverage to ensure that modifying our set of errors is always consistent with the others.

Pros

  • reduces the burden of new/existing contributors smoke testing
  • can be part of git hook to ensure broken changes aren't committed
  • increase in code will be for dev-deps only

Cons

  • possibly a major change, depending on if the directory structure changes, etc.
  • setting up jest (or an equivalent) can be time consuming ditto typescript
  • may increase complexity of a 2.x.x version in the future

Coverage

If implemented, these would be my suggestions for things to test:

  • index.js (single source of truth)
    • all status names have a corresponding code and reason
    • given any code, we can look up the reason
    • given any reason, we can look up the code
  • index.d.ts
    • any exports and/or enums are kept in parity with index.js
  • README.md
    • the table of codes is kept in parity with index.js
    • the table of codes is sorted by status code

I realize these aren't anything particularly pressing, but might be a nice to have / honestly I'd consider working on it later because I have been wanting excuses to do more with tooling and workflows

Thanks!.

Project name is different between Github and NPM

Could you rename the project on github from node-http-status to http-status-codes to match the name on NPM? It's confusing to have 2 names, and it seems perfectly possible to use this without node.

Other than that, this is exactly perfectly what I was looking for to make it easy to remember all the HTTP codes when writing typescript - thanks for a great project.

TypeScript: export union of all codes

In TypeScript it would be useful to have a union type that represents all possible status codes.

This is possible in user land by doing this:

import HttpStatusCodes from 'http-status-codes';

type HttpStatusCodesMap = typeof HttpStatusCodes;
export type HttpStatusCode = Extract<HttpStatusCodesMap[keyof HttpStatusCodesMap], number>;

However it would be nice if the official type definitions provided this out of the box, as I'm fairly sure it's a common requirement. WDYT?

451 Status Code Missing From Typescript Definition File - Missing Library Root Export

Observation

I am on a team that is using this library and my colleague @timsand noticed that 451 was missing from the typescript definition file. We noticed it was mentioned in the documentation:

Screen Shot 2020-09-17 at 9 39 26 AM

Solution

Since this is a typescript project and the definition files are configured to be auto generated in tsconfig, it is clear that the export is missing here: https://github.com/prettymuchbryce/http-status-codes/blob/master/src/index.ts

We will be submitting the fix

Http Code 418

You are missing the most important http code, man :

  • HTTP 418 : "I am a teapot"

Seriously, I was using this funny http code for unit testing... and my test broke when I tried to use your module ...
Not too bad, but I am missing my 418.
:)

ReferenceError: __dirname is not defined

v1.4.0 worked fine.

v2.1.1 throws the following error:

vendor.js:137754 Uncaught (in promise) ReferenceError: __dirname is not defined
    at push../node_modules/http-status-codes/build/index.js.module.exports.527 (vendor.js:137754)
    at Object../node_modules/http-status-codes/build/index.js (vendor.js:137787)
    at __webpack_require__ (vendor.js:105790)

I'm using it like this (example reduced to minimal case):

import { StatusCodes } from "http-status-codes";

console.log(StatusCodes.UNAUTHORIZED);

Culprit: build/index.js:38

/******/ 	__webpack_require__.ab = __dirname + "/";

http-status-codes: 2.1.1
Environment: Ember 3.18
Node: 12.18.3
Browser: Chrome 84

No release information for v2.2.0

For releases up to 2.1.4, there's release notes. Version 2.2.0 was published to npm 9 days ago, but there's no release information on GitHub at all.

Could you please provide such information so that an update to this version can be considered?

Text for code 500 missing "internal"

Not sure if this is intentional, but error text for status code 500 should be "Internal server error" instead of "Server error" - as the official RFC suggests and is used basically everywhere.

Provide an union of type StatusCode.

Right now I have to use the enum StatusCodes to apply type to an property in Typescript like this:

import { StatusCodes } from "http-status-codes";

export type Response = {
  code: StatusCodes;
  error: null | string;
  data: any;
};

The problem with this approach is that enum type is not strict.
You can apply anything to code & it won't throw an error.

response.code = null;
response.code = 99999;
response.code = "big no";

Learn more about this problem :

Providing a union type would be a big help for DX.

Validator function

Hey great package! We're already using it but could really benefit from a util function to validate the code. What do you think ? Would it be valuable to add something like validateHttpCode(code: number): boolean ?

2.1.1 breaking changes on StatusCodes

Migration notes indicate that api changes to StatusCodes are not breaking (but recommended).

In http-status-codes v1, Status Codes were exported directly from the top-level module. i.e. HttpStatus.OK. In v2 all Status Codes live under an object called StatusCodes. i.e. HttpStatus.StatusCodes.OK. We made this change to cater to TypeScript users who prefer a dedicated value with an enum type. The previous values are still exported, but we won't continue to update them. Please migrate if you're using the old-style imports.

However, with either of the following imports HttpStatus.UNAUTHORIZED throws a reference error:

import HttpStatus from 'http-status-codes'
// or
import { HttpStatus } from 'http-status-codes'

Whereas

import { StatusCodes as HttpStatus } from 'http-status-codes';

works as expected.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.