stateProvider using htm5Mode cannot GET error

135 views Asked by At

I am using stateProvider with $locationProvider.html5Mode:

    // Redirect any unmatched url
    $urlRouterProvider.otherwise("/cool");  

    $stateProvider
        // Dashboard
        .state('cool', {
            url: "/cool",
            templateUrl: "views/cool.html"
        });

     $locationProvider.html5Mode(true);

But when I http://localhost:8080/cool I will get Cannot GET /cool error. http://localhost:8080/ and http://localhost:8080/#/cool is working correctly.


After some research I found out the problem is because of grunt connect. so I added modRoute to route all url to index.html:

livereload: {
        options: {
          open: true,
          middleware: function (connect) {
            return [
              modRewrite([
                '!\\.\\w+$ /'
              ]),

but now the problem is every url like http://localhost:8080/uncool to http://localhost:8080/cool.

2

There are 2 answers

0
mausworks On

First, make sure you have the "base"-tag in your head.

<base href="/">

Then make sure that your "/cool"-page serves the same thing as your "/". If not, the server will send back 404 (as expected). This has to be true for all your "sub pages".

To test if this is the case – create a link with a href to "/cool", angular should handle this "internally" with a pushState, which differs from just "browsing" to that page. Meaning, when you click the link, the page will serve as expected, but if you reload (CTRL + R), you will get the error.

0
Andrew On

If you use html5mode you have to include <base> tag in your head part in document. You can set requireBase to false and use html5mode without <base> tag. Please have a look at angular documentation and ui-router documentation