angularjsexpress-routerhtml5mode

Express - enabling catch all for Angular 1.x html5Mode with multiple router files is not working


Okay so this question originates from this post, which is also my question but sorta moved onto this problem.

Now the problem is, my angular app works but when it comes to Node routes, like /login, the browser thinks it's an Angular route. The browser does detect it as a Node route when I refresh the whole page but not when I am navigating the site once Angular routing has kicked in.

Long story short, here are my route files:

require('./routes/routes.js')(express, app);
require('./routes/default.js')(express, app);

routes.js file:

module.exports = function(express, app){
    var router = express.Router();

    router.get('/', function(req, res){
        res.render('index');
    });

    router.get('/login', function(req, res){
        if (req.isAuthenticated()){
            res.render('index');
        } else {
            res.render('login');
        }
});

default.js:

module.exports = function(express, app, passport, Promise){
    var defaultRouter = express.Router();

    defaultRouter.get('/*', function(req, res, next) {
        res.render('./views/index.html');
    });
};

Your help will be very much appreciated.

Thanks


Solution

  • I gave up on making this work on the root URL so I added /index to the baseURL like this:

    index.html file:

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

    The, I added a catch all to the routes.js file, as below:

    module.exports = function(express, app){
        var router = express.Router();
    
        router.get('*', function(req, res, next) {
            if(req.url == '/' || req.url == '/login'){
                next();
            } else {
                res.sendfile('./views/index.html');
            }
        });
    
    
        router.get('/', function(req, res){
            res.render('index');
        });
    
        router.get('/login', function(req, res){
            if (req.isAuthenticated()){
                res.render('index');
            } else {
                res.render('login');
            }
    });
    

    With the angular file of course having this:

    $locationProvider.html5Mode({
        enabled: true,
        requireBase: true
    }).hashPrefix('');
    

    And there. It works like a charm now.

    I hope this helps whoever are in my shoes.