javascriptangularjshtmlsingle-page-applicationhtml5mode

What happens when you enable the html5 mode in mode in angularjs?


What actually happens when you enable the html5 mode ? This might go back to the point how routing takes place in single page applications

What I perceived before(it may be wrong) : Looking at the dirty url in the angularjs application I always assumed it being url fragment to which different views are bind for different fragments. So in short we already have all the pages and a particular fragment is being displayed for a particular url .

Now in order to remove the hash you have to set html5mode true and you have to tell the server to return the index page for every request other than your apis . Kinda like

app.get('/ap1',some);
//more apis 
*
*
*
//in the end
app.get('*' ,(req,res,next) => req.sendFile('index.html'));

Shouldn't the request go the server and the page be reloaded everytime the url changes ?

and what does html5mode does to the browser ? In the newer frameworks like react and angular(2 or greater) , you don't even have to enable html5mode(except in angular 2 where you have to tell what kind of url you want) .

What is this sorcery ?


Solution

  • This uses the History API.

    It is designed so that developers can:

    This updates the browser history and the URL in the address bar without triggering a normal navigation to a fresh page. The idea is that you can provide a smoother, faster transition between pages while still having real URLs that work well if you link to them or come back to them later.

    That way:

    It was designed in response to people using hangbangs instead of real URLs.


    Now in order to remove the hash you have to set html5mode true and you have to tell the server to return the index page for every request other than your apis

    This is terrible advice from Angular.

    It abandons all of the good stuff that the history API can provide in order to have all the drawbacks of hashbangs, but with nicer looking URLs.

    The problem with doing it properly is that it requires duplicating the logic on the server and the client, which is a lot of work. Isomorphic JavaScript is an approach to reduce this workload.


    and what does html5mode does to the browser ?

    Nothing. The html5mode variable is read by Angular. The browser doesn't care about it directly. It tells Angular to use the History API instead of hangbang URLs.


    In the newer frameworks like react and angular(2 or greater) , you don't even have to enable html5mode(except in angular 2 where you have to tell what kind of url you want) .

    They just use the History API by default.