简体   繁体   中英

html5mode Angular giving exception

I am building a website in Angular 1.5.5 and want to have pretty url (without #). Following the instructions on some other posts, I added Html5mode to be router along with base url in the index.html

    $locationProvider.html5Mode(true).hashPrefix('!');
    <base href="innovationglobal"> 

However, I get the following exception :

Error: Failed to execute 'replaceState' on 'History': A history state object with URL ' http://home/ ' cannot be created in a document with origin ' http://localhost:8080 '. at Error (native) at Yf.k.url (lib/1.5.5/angular.min.js:47:311)

After changing your tag to an absolute URL or path

<base href="innovationglobal">

either by adding / or https://

<base href="/innovationglobal/">

now when you reload the page, the browser will send a request to the server for your current path: /innovationglobal/

You need to set up your server to handle that path --and any other path your Angular app may put into the browser address bar. That could be /innovationglobal/users/ or /innovationglobal/products/detail/ etc.

Because the user may press F5 to reload on any page they are viewing. And that would take control away from your Angular app, and send the request for that URL to the server.

So you need to set up your server with a catch-all. Whatever the path in the address bar, your server should reply with the index.html of your Angular app.

But careful, you need to make an exception for your static assets (files like .js and .css). For nginx, that would looks somewhat like this:

location = /static/ {
    alias /var/www/static/;
    try_files $uri $uri/ =404;
}
location /innovationglobal/ {
    root /var/www/innovationglobal;
    try_files $uri /app/index.html =404;
}

Depending on the web server you are using.

Have you tried enable html5Mode without using a base:

$locationProvider.html5Mode({
  enabled: true,
  requireBase: false
});

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