简体   繁体   English

有没有一种方法可以使用JS和AngularJS获取HTTP状态代码名称?

[英]Is there a way to get HTTP status code name using JS and AngularJS?

I have an AngularJS, JS, JQ, HTML5, CSS3 web app. 我有AngularJS,JS,JQ,HTML5,CSS3网络应用程序。 It is suposed to send different HTTP methods to REST API of our projects and manipulate them. 可以将不同的HTTP方法发送到我们项目的REST API并对其进行操作。 It has similar behavior to DHC by Restlet (formerly Dev HTTP Client) . 它具有与Restlet(以前称为Dev HTTP Client)的DHC相似的行为。 Every request returns a status code like 200, 201, 404, 500 etc. which is then displayed to the user. 每个请求都返回一个状态码,例如200、201、404、500等,然后将其显示给用户。

Now what I would like is to display not only a response code, but also a description of it like this: 现在,我想要的不仅是显示响应代码,而且还要显示如下描述:

404 Not Found , 201 Created etc. 404 Not Found201 Created等。

I am getting a response from Angular like this: 我从Angular得到这样的答复:

$http(config).success(function (data, status, headers, config) {//some logic}

Does anyone know if this is possible using AngularJS? 有谁知道使用AngularJS是否可行?

Well, I ended up with the following solution: 好吧,我最终得到了以下解决方案:

I created a constant variable and listed all HTTP codes and their description (you can copy them to your own program): 我创建了一个常量变量,并列出了所有HTTP代码及其描述(您可以将它们复制到自己的程序中):

constants.js: constants.js:

var HTTP_STATUS_CODES = {
        'CODE_200' : 'OK',
        'CODE_201' : 'Created',
        'CODE_202' : 'Accepted',
        'CODE_203' : 'Non-Authoritative Information',
        'CODE_204' : 'No Content',
        'CODE_205' : 'Reset Content',
        'CODE_206' : 'Partial Content',
        'CODE_300' : 'Multiple Choices',
        'CODE_301' : 'Moved Permanently',
        'CODE_302' : 'Found',
        'CODE_303' : 'See Other',
        'CODE_304' : 'Not Modified',
        'CODE_305' : 'Use Proxy',
        'CODE_307' : 'Temporary Redirect',
        'CODE_400' : 'Bad Request',
        'CODE_401' : 'Unauthorized',
        'CODE_402' : 'Payment Required',
        'CODE_403' : 'Forbidden',
        'CODE_404' : 'Not Found',
        'CODE_405' : 'Method Not Allowed',
        'CODE_406' : 'Not Acceptable',
        'CODE_407' : 'Proxy Authentication Required',
        'CODE_408' : 'Request Timeout',
        'CODE_409' : 'Conflict',
        'CODE_410' : 'Gone',
        'CODE_411' : 'Length Required',
        'CODE_412' : 'Precondition Failed',
        'CODE_413' : 'Request Entity Too Large',
        'CODE_414' : 'Request-URI Too Long',
        'CODE_415' : 'Unsupported Media Type',
        'CODE_416' : 'Requested Range Not Satisfiable',
        'CODE_417' : 'Expectation Failed',
        'CODE_500' : 'Internal Server Error',
        'CODE_501' : 'Not Implemented',
        'CODE_502' : 'Bad Gateway',
        'CODE_503' : 'Service Unavailable',
        'CODE_504' : 'Gateway Timeout',
        'CODE_505' : 'HTTP Version Not Supported'
    };

And then in my AngularJS controller, when I receive a status from $http I just call this function, which set's the value of status code message to a model: 然后在我的AngularJS控制器中,当我从$http收到状态时,我只调用此函数,该函数将状态代码消息的值设置为模型:

setResponseCodeDescr = function(responseCode) {

var responseCodeConstant = 'CODE_'.concat(responseCode);

if (HTTP_STATUS_CODES[responseCodeConstant]){
    $rootScope.response.description = HTTP_STATUS_CODES[responseCodeConstant];
} else {
    $rootScope.response.description = "";
}

}

That's all :) 就这样 :)

When making the call with Angular, you get the status code back, with the status variable you showed in your success function. 当使用Angular进行调用时,您将获得状态代码以及在成功函数中显示的status变量。 Angular does not seem to return the text to go with it to you, in any way I have seen. 以我所见的任何方式,Angular似乎都不会将文本返回给您。

You could do it with a switch statement to display the message to go with the code, but obviously the can be a long switch statement for all possible codes. 您可以使用switch语句来执行此操作,以显示与代码一起显示的消息,但是显然,对于所有可能的代码而言,switch语句可能很长。 You also could return the message you want to display as part of the data, which is nothing more than putting the work around on your backend instead of the front end. 您还可以返回要显示为数据一部分的消息,这只不过是将工作放在后端而不是前端。

As far as doing the translation from code to message, I would suggest placing it in a directive (or filter) and reuse that across your app to take a code and return the message to go with it to show in the UI. 至于从代码到消息的转换,我建议将其放在指令(或过滤器)中,并在整个应用程序中重复使用,以获取代码并返回消息以与之一起显示在UI中。

I'd make as suggested by "amenoire/Jason C", but the constants 我会按照“ amenoire / Jason C”的建议做,但是常数

var HTTP_STATUS_CODES = {
        '200' : 'OK',
        '201' : 'Created'
...
        '505' : 'HTTP Version Not Supported'
};

wrote without prefix "CODE_" and call them as 写没有前缀“ CODE_”,并以

var s =  HTTP_STATUS_CODES[xmlhttp.status]
if (!(s && s.length > 0)) s = 'look at https://developer.mozilla.org/en-US/docs/Web/HTTP/Status'

If I'm not wrong, you can still use jQuery ajax for your call, and setup your response with $.ajaxSetup like this: 如果我没看错,您仍然可以使用jQuery ajax进行通话,并使用$ .ajaxSetup设置响应,如下所示:

$.ajaxSetup({
    type: "GET",
    dataType: "jsonp",
    error: function(xhr, exception){
        if( xhr.status === 0)
            alert('Error : ' + xhr.status + 'You are not connected.');
        else if( xhr.status == "201")
            alert('Error : ' + xhr.status + '\nServer error.');
        else if( xhr.status == "404")
            alert('Error : ' + xhr.status + '\nPage note found');
        else if( xhr.status == "500")
             alert('Internal Server Error [500].');
        else if (exception === 'parsererror') 
            alert('Error : ' + xhr.status + '\nImpossible to parse result.');
        else if (exception === 'timeout')
            alert('Error : ' + xhr.status + '\nRequest timeout.');
        else
            alert('Error .\n' + xhr.responseText);
    }
});

Getting the code technically, seems easy though, "just attaching the inbuilt properties of the response will get you the description". 从技术上来说,获取代码似乎很容易,“仅附加响应的内置属性将为您提供描述”。

It's explained in the docs actually, once you have the response along with its properties, you can do anything with it. 实际上在文档中对此进行了解释,一旦您获得了响应及其属性,就可以对其进行任何操作。 And the other way is creating a CONSTANT, but I don't think we usually need so much. 另一种方法是创建一个常量,但我认为我们通常不需要那么多。

$http({
    method: 'GET',
    url: '/someUrl'
}).then(function successCallback(response) {
    var status = response.status;
    console.log(status); // gives the status 200/401
    var statusText = response. statusText;
    console.log(status); // HTTP status text of the response
}, function errorCallback(response) {

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM