【问题标题】:api get request, handle 404api获取请求,处理404
【发布时间】:2018-01-11 21:46:08
【问题描述】:

我正在研究处理来自 api 调用的 404 请求,当它发生时我将返回 html。

$http.get('/api/house/' + $routeParams.id)
   .then(function (res) {

    $scope.houses = res.data;

}, function (err) {

    //when not found I am binding html from response
    if(err.status == 404){  
        $scope.errHtml = $sce.trustAsHtml(err.data);
    }

});

为 404 返回 html:

<!doctype html>
<html>
<head>

   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" type="text/css" href="/resources/css/bootstrap.min.css">

   <title>404</title>

</head>
<body>

    <div>test 404</div>

</body>
</html>

在我看来:

<div ng-bind-html="errHtml"></div>

我试图了解这是否是在 Angular js 中处理来自 api 调用的 404 的最佳方法

【问题讨论】:

  • 你不喜欢页面中的“”。创建状态的更好方法,然后在错误函数中使用 state.go("pageNotFound");
  • 我没有那个 UI 路由器吗?
  • 您使用什么技术进行路由?
  • 角度 $routeProvider
  • 你可以使用 $location.url('/error')

标签: javascript html angularjs http-status-code-404


【解决方案1】:


在 angularjs 中处理错误响应的最佳方法是编写 $http interceptor。只需编写一个拦截器服务并将其推送到$httpProvider 拦截器,然后您就可以在一个地方处理所有错误。
请参阅文档here 代码如下所示

.factory('httpRequestInterceptor', function ($q, $location) {
    return {
        'responseError': function(rejection) {
            if(rejection.status === 404){
                $location.path('/404/');                    
             }
            return $q.reject(rejection);
         }
     };
});

然后,您可以将此服务注入到配置块中的interceptor

.config( function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequestInterceptor');
});


您也可以在此处处理其他错误代码并相应地重定向。希望这会有所帮助。

【讨论】:

  • 这也将重新定位到 /404 并且不会保留路线
  • 您可以有一条路线.when("/404", { templateUrl : "404.html" }) 并使用`$location.path('/404'); 将用户引导到那里或者如果您想显示一些错误警报,您可以在此处执行相同操作,而无需重定向到 404@user1751287
  • 我确实有,但我也有后端 404 处理程序,因此在拦截路由变为 websites.com/404
  • 那么,一旦出现错误,你要显示什么? @user1751287
  • 我认为ng-route 没有标准的方式来实现这一点。
猜你喜欢
  • 2014-09-10
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 2017-10-06
相关资源
最近更新 更多