简体   繁体   中英

How to properly routing for SPA using Angular 1.5?

I'm new to angular. I create a blog for showing my profile. In my website, I have several component and my app.module has a configuration for the routing, as shown:

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: "/"
    })
 });

Here is an example of my component:

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

I tried to locally run the server using python -m SimpleHttpServer so that I can access my local website using browser to localhost:8000 , When I click a link from my homepage, the page is correctly loaded. However, when I initially access my website using different urls (eg localhost:8000/testing ) Angular route doesn't seem to work properly. I get this error instead,

在此处输入图片说明

How do I set the router so that those urls can be redirected to my homepage?

Given you have enabled html5 mode I think you may need to set your server up so that regardless of the path it will return your index.html file.

For example, when your server receives a request for a resource at localhost:8000/testing it will return index.html.

From the AngularJS documentation:

Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (eg index.html). Requiring a tag is also important for this case, as it allows Angular to differentiate between the part of the url that is the application base and the path that should be handled by the application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM