jmls jmls -4 years ago 123
AngularJS Question

angular ui-router, html5 mode always refreshes to /

I am trying to use html5mode in angular, so that I can bookmark a page like http:/myhost/products (where /products is a route defined by$stateProviderRef.state(xxx) ).

To that end I've


  • added $locationProvider.html5Mode(true) to my app config

  • added 'base href="/"' (with the <>) to my index.html

  • added the catch all rewrite to my server.js in node.js

    app.get('*', function(req, res) {
    res.redirect('/');
    });

  • restarted the node server



so what happens is that the app starts ok, all navigation works, I can go to http://myhost/products and everything works well.

However, if I press refresh at this point, I am redirected back to the index page. Looks to me as if ui-router is either losing the path (/products) or I have missed something in the config / setup

I have been browsing through the questions on StackOverflow until my eyes are bleeding, but all of the solutions to similar problems are things that I've already done (base=, redirect etc)

Anyone else has this problem and solved it ? Would be much appreciated if you could share your findings.

Thanks

Answer Source

You shouldn't redirect in server like that

app.get('*', function(req, res) { res.redirect('/'); });

Instead, send same index.html

app.route('/*')
    .get(function(req, res) {
      res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
    });

Take a look at this generator for more

https://github.com/DaftMonk/generator-angular-fullstack/blob/master/app/templates/server/routes.js

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download