I have a node app that has Express routes. These hand off to AngularJS routes that conditionally load partials for the one-page front-page app, or to a login page if there is no session.
I explored using AngularJS $locationProvider
to remove the hash character from URLs, so that I could have cleaner addresses. I looked at the module adjustments made in the answer to this question: Removing the fragment identifier from AngularJS urls (# symbol)
When doing this, this interferes with the routes set up at the Express level. The side effect is that the application no longer routes to the login page. So the following Express-side logic gets ignored:
app.get('/', function(req, res) {
if (req.session.user) {
res.render('index', { username : req.session.username, msg : req.session.msg });
}
else {
res.redirect('/login');
}
});
(The /login
path has its own Express route.)
In other words, the application works as if a user is always logged in, because AngularJS's $routerProvider
takes over and shows the (logged-in) front page:
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl : '/partials/front/front.html',
controller : 'FrontPageController',
controllerAs : 'vm'
})
...
.otherwise({redirectTo: '/'});
}
If I have to keep hashed URLs, is there a way to deal with Express routes so that I can get to what is after the hash?
For instance, I have the following address that Express loads as the /
GET route, and is then handled on the AngularJS side to load a viewer
-specific partial into the /
(front) page:
https://foo.com/#/viewer?id=1234
What I'd like to do is go to the Express routes and deal with the /
GET request so that I can parse out what is after the hash and redirect after login.
Basically, I want the following kind of logic:
app.get('/', function(req, res) {
if (req.session.user) {
res.render('index', { username : req.session.username, msg : req.session.msg });
}
else {
if (req.query.id) {
res.redirect('/login?t=viewer&id=' + req.query.id);
} else {
res.redirect('/login');
}
}
});
But it looks like req.query.id
gets wiped before I have a chance to extract its value for the redirect call.
Is there any way to grab the URL before it gets wiped by Express, so that I can parse it?
Failing that, is there a way to make AngularJS and Express routes play nice together if I remove the fragment identifier (hash)?