AngularJS – 为什么当更改url$ routeProvider似乎不工作,我得到一个404错误

我的$routeProvider是这样configuration的:

 teachApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider. when('/teach/', {templateUrl: 'views/login_view.html'}). when('/teach/overview', {templateUrl: 'views/overview_view.html'}). when('/teach/users', {templateUrl: 'views/users_view.html'}). otherwise({redirectTo: '/teach/'}); $locationProvider.html5Mode(true); }]); 

在应用程序中,如果我点击<a href="/teach/overview">Overview</a>等链接,概览部分将按预期显示。 但是,当我手动将地址栏中的URL更改为完全相同的URL时,出现404错误。 $routeProviderconfiguration不正确?

我使用MAMP本地主机的应用程序的根url是http://localhost/teach/

你需要设置你的Apache来重定向到根的所有路径 。

当您直接打开http://localhost/teach/overview您的Web服务器正尝试从未定义的路由中提供页面。

当在一个角度的应用程序,你点击一个链接href路径的http://localhost/teach/overview ,Angular步骤,而不是让你的浏览器从服务器请求一个页面拦截你的点击事件,并去您的routeProvider查看要显示哪个客户端视图(这就是为什么他们称之为“单页面应用程序”)。 这就是为什么你的链接工作,只要你不尝试直接打开它们。

除了Apache配置,你可能还想使用href值为/teach/ base标签:

 <base href="/teach/" /> 

这样你可以让你的routeProvider不受固定前缀的限制:

 teachApp.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) { $routeProvider. when('/', {templateUrl: 'views/login_view.html'}). when('/overview', {templateUrl: 'views/overview_view.html'}). when('/users', {templateUrl: 'views/users_view.html'}). otherwise({redirectTo: '/'}); $locationProvider.html5Mode(true); }]); 

您也可以在您的网址中使用#。

 http://localhost/teach/#/overview 

这不会向服务器发送请求,而是被Angular $ routeProvider拦截。