如何使用Angular 1.5正确路由SPA?

时间:2016-12-21 23:35:15

标签: javascript angularjs single-page-application ngroute

我是棱角分明的新人。我创建了一个博客来显示我的个人资料。 在我的网站中,我有几个组件,我的app.module有一个路由配置,如下所示:

app.config(function($locationProvider, $routeProvider){
  $locationProvider.html5Mode({
    enabled:true,
    requireBase: false
  })

  $routeProvider.
    when("/", {
      template: "<research-overview></research-overview>"
    }).
    when("/research-interests", {
      template: "<research-interests></research-interests>"
    }).
    otherwise({
      redirectTo: "/"
    })
 });

以下是我的组件示例:

angular.module('researchOverview', [])
  .component('researchOverview', {
     templateUrl: '/templates/research-overview.html',
});

我尝试使用python -m SimpleHttpServer在本地运行服务器 这样我就可以使用浏览器访问我的本地网站localhost:8000,当我点击主页上的链接时,页面被正确加载。但是,当我最初使用不同的网址(例如localhost:8000/testing)访问我的网站时,Angular路线似乎无法正常工作。 我反而得到了这个错误,

enter image description here

如何设置路由器以便将这些网址重定向到我的主页?

1 个答案:

答案 0 :(得分:0)

鉴于您已启用html5模式,我认为您可能需要设置您的服务器,以便无论路径如何,它都会返回您的index.html文件。

例如,当您的服务器在localhost:8000 / test接收资源请求时,它将返回index.html。

来自AngularJS文档:

  

使用此模式需要在服务器端重写URL,基本上是您   必须重写所有链接到您的应用程序的入口点   (例如index.html)。要求标签对此也很重要   case,因为它允许Angular区分部分   url是应用程序库和应该处理的路径   通过申请。