AngularJS and Express Routing issue

All we need is an easy explanation of the problem, so here it is.

I’m using AngularJS and ExpressJS and having an issue with routing. I saw many other posts but none of those solutions seemed to work. Here is my routes in Express:

module.exports = function(app, auth) {
    //Api routes
    var mycontroller = require('../app/controllers/mycontroller');
    app.get('/api/dostuff/:id', mycontroller.getBlockByHash);

    //Home route
    app.get("/", function(req, res) {
      res.render('index');
    });
  };

When I go to my root /, everything works as expected. ExpressJS serves up my index and angular picks up the rest. When I click a link /blocks, it works as expected since AngularJS picks up the route. But when I refresh, I get a 404 not found error.

I tried app.get('*' instead, but that gives me a completely different error where nothing loads.

enter image description here

I’m using Jade to create the basic page structure with Express. My Express config is:

app.use(express.favicon());
app.use(express.static(config.root + '/public'));

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

When using html5Mode the documentation says:

Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)

What it doesn’t mention is:

  • You should exclude static assets like scripts/styles/images/fonts etc.
  • You should also exclude your Restful API.

Your case:

The error you got there is express serving html into script tags and the browser fails to parse them as a valid javascript.

Use express.static to serve static assets and then use app.get('*', for redirecting all other requests to your angular.js entry point (index.html).

express.js middleware order do counts!

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply