在 Angular 中返回 404

Returning 404 in Angular

当您访问不存在的页面时,我很熟悉 returning 404 作为 HTTP 状态代码。当您构建静态网站时,它运行良好且有意义,但在 Angular 中则有所不同。

假设我访问了 /blah,但它不在我的路线列表中 - 然后我重定向到 /not-found。但是假设我访问了一个像 /stuff/123 这样的有效 URL,但是我的后端中不存在对象 Stuff123。然后我应该手动在我的 StuffController$location.path('/not-found')?

这是我现在的配置:

app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider
    .when('/stuff/:id', {
        templateUrl: '/views/stuff.html',
        controller: 'StuffController'
    })
    .when('/not-found', {
        templateUrl: '/views/not-found.html'
    })
    .otherwise({
        redirectTo: '/not-found'
    });
});

另外,在Angular中return404有意义吗?如果是这样,那我该怎么做?

Should I then manually make a redirect in my StuffController with $location.path('/not-found')?

我不会重定向到未找到的路由。如果对象 Stuff123 不存在,它仍然不意味着 找不到路由 。它 被发现 ,只是没有这个特定参数的数据。你应该只显示适当的相应消息。

或者这样想。未找到是 404 状态代码。这是 错误 代码。但是,您描述的不是错误情况,只是缺少此 ID 的数据。因此,在经典应用程序中,您应该是 SUCCESS 200,只有空响应 [] 数据。所以又不是 "not found".

我知道这有点旧,但我通过查找 404 和 angular 很容易找到它,所以....

我认为您想回到使用 'catch all' 路线时想要做的事情。包罗万象的路线是“**”。所以把这样的东西放在你的应用程序模块中......

        },
        {
            path: 'admin/orders',
            component: AdminOrdersComponent,
            canActivate: [AuthGuard, AdminAuthGuard]
        },
        { path: '**', component: CatchAllComponent }

通过这种方式,您可以在模板中为用户提供有用的信息,无论他们在犯错误后在地址栏中输入什么内容。