javascript 访问 http 状态码常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18765869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing http status code constants
提问by Johan
I'm looking for a list of http status codes in Javascript. Are they defined in any implementation?
我正在寻找 Javascript 中的 http 状态代码列表。它们是否在任何实现中定义?
I've had a look at XMLHttpRequest
, but only found readyState
constants.
我看过了XMLHttpRequest
,但只找到了readyState
常量。
var xhr = new XMLHttpRequest();
console.log(xhr.DONE); //4
I'm looking for something like
我正在寻找类似的东西
console.log(xhr.statusCodes.OK); //200
Which obviously doesn't exist on the xhr object.
这显然不存在于 xhr 对象上。
采纳答案by Jamiec
Http status codes are maintained by the Internet Assigned Numbers Authority (IANA), whereas readyState
is specific to XmlHttpRequest
.
Http 状态代码由 Internet 号码分配机构 (IANA) 维护,而readyState
特定于XmlHttpRequest
.
Therefore just go to a reputable source. The wikipedia articleshould suffice as this is not really a contentious topic - or, as commented, the official list can be found here
因此,只需前往信誉良好的来源即可。在维基百科的文章应该足够,因为这是不是一个真正的争议话题-或者,如评论,可以发现正式名单在这里
You could also wrap those you are interested in into a javascript object
您也可以将您感兴趣的内容包装到一个 javascript 对象中
var HttpCodes = {
success : 200,
notFound : 404
// etc
}
usage could then be if(response == HttpCodes.success){...}
然后可以使用 if(response == HttpCodes.success){...}
回答by mpolci
For node.js you can use the module node-http-status(github).
对于 node.js,您可以使用模块node-http-status( github)。
This is an example:
这是一个例子:
var HttpStatus = require('http-status-codes');
response
.status(HttpStatus.OK)
.send('ok');
response
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.send({
error: HttpStatus.getStatusText(HttpStatus.INTERNAL_SERVER_ERROR)
});