【问题标题】:Angular Routing only works for one caseAngular Routing 仅适用于一种情况
【发布时间】:2016-06-08 10:56:45
【问题描述】:

所以我正在尝试为我的项目使用角度路由,但似乎只有一条路由正常工作。如果我使用 'localhost/#/{{routeName}}',我可以访问任何路由,但是当我使用格式 'localhost/{{routeName}}' 时,除了 home 之外的所有内容都会返回 404 错误。这是我的配置

angular.module('shasta-water', ['search', 'ngRoute']).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
      $locationProvider.html5Mode(true);

      $routeProvider
        .when('/', {
          redirectTo: '/home'
        })
        .when('/home', {
          templateUrl: 'Templates/HomeTemplate.html'
        })
        .when('/search', {
          templateUrl: 'Templates/SearchTemplate.html',
          controller: 'searchCtrl'
        })
        .when('/add', {
          templateUrl: 'Templates/AddTemplate.html'
        })
        .otherwise({
          // templateUrl: 'Templates/ErrorTemplate.html'
          redirectTo: '/home'
        });

    }]);

【问题讨论】:

  • 您确定模板文件可用吗?
  • @Ties 是的,我可以使用 localhost/#/search 和 localhost/#/add 访问文件,但如果我只使用 localhost/search 或 localhost/add 则它们不起作用
  • 您使用的是哪种后端? Apache/PHP 还是 Node?​​span>
  • 您需要向您的服务器添加一些代码,它可以理解您的请求。我自己不了解 ASP.NET,但发现了这个:stephenwalther.com/archive/2015/01/16/…
  • @Ties 哦,太好了,谢谢!我现在会调查一下

标签: angularjs asp.net-mvc routing


【解决方案1】:

您需要确保服务器也知道当您使用 HTML5 模式(不带 #)时它接收到的请求的这些 url 会做什么,您可以通过以下方式执行此操作:

Apache/PHP

在您的根文件夹中的.htaccess 文件中。在 index.php 中处理路由

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]

RewriteRule ^(.*) /index.php [NC,L]

发件人:https://stackoverflow.com/a/22740184/5171528

ASP.NET

 <!-- from https://stackoverflow.com/questions/25916851/wrapping-staticfilemiddleware-to-redirect-404-errors -->

<configuration>
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" />
  <rewrite>
    <rules>
      <!--Redirect selected traffic to index -->
      <rule name="Index Rule" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_URI}" matchType="Pattern" pattern="^/api/" negate="true" />
        </conditions>
        <action type="Rewrite" url="/index.html" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>
</configuration>  

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多