【问题标题】:$Http.get(), how to deal with 404 response from WebAPI$Http.get(),如何处理来自 WebAPI 的 404 响应
【发布时间】:2016-09-30 13:52:27
【问题描述】:

在我的 Web 应用程序中,我对远程 HTTP WebAPI 服务执行 GET 命令

$http.get(url).then(function(data) { do_something(); });

当 WebAPI 返回一些数据时一切正常,但是当 WebAPI 返回 404 错误(没有数据可显示)时,该函数似乎没有触发。 如何为其设置回调?

【问题讨论】:

    标签: javascript angularjs ajax http web-applications


    【解决方案1】:
    $http.get(url).then(function(data) {
      do_something();
    }, function(err) {
      // your error function
      if (err.status == 404) {
        do_something_else();
      }
    });
    

    【讨论】:

      【解决方案2】:

      我认为对于 404 响应,最好的办法是显示正确的未找到页面。在 angularjs 中,您可以使用 $injector 服务拦截响应。因此,您可以创建一个查找 404 响应并显示 404 页面的服务。

          angular.module('mymodule')
      
          .service('APIInterceptor', function( $injector) {
            return {
             'request': function(config){
                 // request logic goes here.
             },
             'responseError' : function(response){
                if (response.status === 404) {
                  $injector.get('$state').go('error_500');
                }
              return response;
             }
           };
          });
      

      【讨论】:

        【解决方案3】:

        $http 返回状态码作为第二个参数。

        $http.get(url)
          .success(function(data, status) {
              alert(status);
          })
          .error(function(data, status) {
              alert('Error with status code: ' + status); 
          });
        

        status{number} – 响应的 HTTP 状态代码。

        但是如果status是错误状态,比如404,那么就会调用错误块

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-22
          • 2020-04-05
          • 1970-01-01
          • 1970-01-01
          • 2017-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多