【问题标题】:Angular 404 page when navigated path does not begin with <base> path导航路径不以 <base> 路径开头时的 Angular 404 页面
【发布时间】:2016-09-16 21:42:01
【问题描述】:

似乎无法解决这个 Angular 和 UI-Router 问题。我正在尝试为我的 Angular 应用程序设置一个自定义 404 页面,但在极端情况下,Angular 会抛出错误而不是处理路由。

我的网址是:http://www.example.com/

我要求应用程序应该有一个基本路径,所以我使用 .NET URL Rewrite 将所有流量重定向到正确的位置:

http://www.example.com/app/

为了完成这项工作,我在我的 HTML 头部部分中使用了 &lt;base&gt; 标记,如下所示:

<base href="/app/">

现在我所有的状态都使用 /app/ 前缀。

$stateProvider
// https://www.example.com/app/
.state('/', {
    url: '/',
    templateUrl: '/Partials/Pages/Home',
  })


  // https://www.example.com/app/login
  .state('login', {
    url: '/login',
    templateUrl: '/Partials/Pages/Login',
  });

为了让我的 404 页面正常工作,我定义了我的最后一个状态来拦截任何无法识别的路径:

// If no state is matched, load the 404 error
$stateProvider.state('404', {
    url: '*path',
    templateUrl: '/Partials/Pages/PageNotFound',
  });

这几乎可以完美运行。以下 URL 返回我的 404 错误: https://www.example.com/app/sdfsf

但是,任何不以我配置的基本路径开头的路径都不会重定向到 404 错误。以下路径返回 Angular 错误: https://www.example.com/login

对于不以我的基本路径开头的任何 URL,有没有办法处理 404 错误?

【问题讨论】:

    标签: javascript angularjs angular-ui-router


    【解决方案1】:

    首先,您的这部分代码存在矛盾:

    // For any unmatched url, redirect to home
    $urlRouterProvider.otherwise('/');
    
    // If no state is matched, load the 404 error
    $stateProvider.state('404', {
        url: '*path',
        templateUrl: '/Partials/Pages/PageNotFound',
      });
    

    你应该做的是与其他人一起定义你的“404”状态,否则应该重定向到它:

    $stateProvider
    // https://www.example.com/app/
    .state('/', {
        url: '/',
        templateUrl: '/Partials/Pages/Home',
      })
    
    
    .state('404', {
        url: '/404',
        templateUrl: '/Partials/404.html',
      });
    $urlRouterProvider.otherwise('/');
    

    【讨论】:

    • 首先,这仍然不适用于前面没有 &lt;base&gt; 路径的任何路径,这是我的主要问题。所以https://www.example.com/asdasd 仍然会引发 Angular 错误并导致应用程序崩溃。但是任何路径https://www.example.com/app/asdasd 都运行良好。我已经删除了有关使用 .otherwise 的详细信息,因为您是对的,这是不必要的。
    • 您无法访问“基本”网址之前的任何内容,因为您的应用无法处理这些内容。你能向我解释一下你的应用程序是如何服务的吗?您如何将域链接到您的应用程序?
    • ^ 这就是答案。您能否将其添加为新回复,我会接受。
    猜你喜欢
    • 2014-11-30
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    相关资源
    最近更新 更多