简体   繁体   中英

AngularJS routes returns 404 error when page is being refresh

I am new to angularJS and I love coding with it. I am currently building now a web-portal using angularJS, and each of my pages uses ngRoute . It works fine for me but when I tried to refresh the page it returns me an 404 error / page not found . What should I do on this issue? Here's my code:

var app = angular.module("CVSRRC", ['ngMaterial','ngRoute']);

app.controller('CVSRRC-CTRL', function($scope, $http, ...){
    // some codes here...
});

app.config(function($routeProvider, $locationProvider){
    $locationProvider.html5Mode(true).hashPrefix('!');

    $routeProvider
    .when('/', {
        templateUrl: '_pages/home',
        controller: 'homeCTRL',
        resolve: {
           delay: function($q, $timeout){
                var delay = $q.defer();
                $timeout(delay.resolve, 1000);
                return delay.promise;
           }
        }  
    })
    ...etc...
    .otherwise({
         redirectTo: '/'
    });
});

and in my HTML

<html>
   <head>
       <base href="/cvsrrc/" />
   </head>
   <body ng-app="CVSRRC" ng-controller="CVSRRC-CTRL">

      <div class="row" id="main">
        <div ng-view ng-show="statechange"></div>
        <div ng-show="!statechange" cvsrrc-resolve>
            <div id="_loader_"></div>
        </div>
    </div>

   <a href="about-us">About</a>
   <a href="login">login</a>
   //etc
   </body>
 </html>

And here's my .htaccess looks like

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
ErrorDocument 404 http://localhost/cvsrrc/page-not-found

Since you have used <base href="/cvsrrc/" /> and $locationProvider.html5Mode(true).hashPrefix('!'); your url removed #! from url and adds cvsrrc/. so it will work if you redirect app from app.

But when you reload page it will try use url with cvsrrc/ to find path which not actually there.

So you have to use rewrite module on your server to tell to redirect cvsrrc/ to #!/

Try either:

  1. Removing resolve from your route.
  2. Add below code after config:

    $locationProvider.hashPrefix("");

  3. Share the url you are using to access the page.

  4. Remove the ending "/" in your base.

Finally I found a solution, I already met this solution before but It doesn't work for me because I forget to remove the /localhost/ from the .htaccess ! Here it is:

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On
    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d

    RewriteRule ^ - [L]

    RewriteRule (.*) /cvsrrc/index.php [L]
</IfModule>

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