3

I was trying to remove '#' from URL. I looked through a lot of example doing so. Almost all examples followed same 2 steps which I followed.
Step 1: Enable HTML5 mode

.config(function ($routeProvider,$locationProvider){
$routeProvider
  .when('/', {
    templateUrl: 'views/main.html',
    controller: 'MainCtrl',
    controllerAs: 'main'
  })
  .when('/products/',{
    templateUrl:'views/HomeMain/products.html',
    controller:'MainCtrl',
    controllerAs:'main'
  });   
$locationProvider.html5Mode(true);
})

Step 2: Add basetag

<head>
  <base href="/">
</head>

After following above mentioned steps I successfully removed '#' from the URL.
Whenever I navigate to 'products' page URL looks like
http://localhost:9001/products/
which is exactly what I want.
But, whenever I reload products page, this error is displayed in the browser window:

Cannot GET /products/

Why am I receiving this error? How do I handle this error?

Chirag
  • 179
  • 3
  • 16

3 Answers3

0

When using # you are browsing in client side and urls are never sent to server. However when you use html5Mode, you should also configure server side, to rewrite to urls and tell client will handle it

For asp.net see this

Community
  • 1
  • 1
asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84
0

You had a URL like http://localhost:9001/#/products/ before enabling the HTML5 mode. Please note that the contents of the hash are never submitted to the server. So what was requested from the server was http://localhost:9001 only.

As soon as server returns response, and angular takes over the control, it sees the /products/ fragment of the hash, and reacts accordingly.

After enabling HTML5 mode, your URL becomes http://localhost:9001 for your home page. Then you visit the route for products, which makes your URL http://localhost:9001/products/. Please note that because HTML5 mode uses browser's history API, your page is not refreshed entirely, even if the URL (not the hash fragment) is changed.

Now, if you refresh your page, what server receives is http://localhost:9001/products/, and since this route is not handled on the server, it returns a 404 error.

For making this to work, you need to implement logic to return appropriate contents when this route is visited. For Node based apps, you can follow this answer.

Community
  • 1
  • 1
31piy
  • 23,323
  • 6
  • 47
  • 67
0

This is because the web server receiving the request looks for a resource matching the full url on the server, which doesn't exist because the angular portion of the url refers to a route in your angular application and needs to be handled in the client browser.

You can do a URL Rewrite if using NodeJS/ExpressJS/IIS. Refer this blog for the solution: http://jasonwatmore.com/post/2016/07/26/angularjs-enable-html5-mode-page-refresh-without-404-errors-in-nodejs-and-iis

RushabhG
  • 352
  • 3
  • 11