I am working on learning authentication using Angular 1 and Express. I've got my backend set up for testing purposes, and i'm now working on the front end. I've got basic routes set up.
This is the core to my front end:
function router($stateProvider, $urlRouterProvider, $locationProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: 'views/home/',
controller: 'mainController'
})
.state('login', {
url: '/login',
templateUrl: 'views/login/',
controller: 'loginController'
});
$locationProvider.html5Mode(true);
}
And here are the routes on the back end that would be relevant:
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req,res){
res.sendFile(path.join(__dirname, 'public/', 'index.html'));
});
The only other routing I have is for my API, which use the constant apiRouter and inject /api/ into those routes.
Now, the issue comes when I try to access a route directly from the browser. I've I nagivate to localhost:8080/login I get the error Cannot GET /login, but using a ui-sref on my index page, it seems to work just fine.
Any ideas?
So I figured out what my issue was.
After my root path GET statement in my server file, I need to add the following code:
app.get('*', function(req,res){
res.sendFile(path.join(__dirname, 'public/', 'index.html'));
});
What was happening, is that Express was trying to find a /login route that I had defined. The problem is, that route needs to be handled by Angular, and not Express, so the '*' is a catch-all for any route that Express doesn't know how to explicitly handle, it then hands off that responsibility to the index.html file.