MattDionis MattDionis - 10 days ago 7
Node.js Question

Angular 'Cannot GET' route on page refresh

I have a search function within my Angular app that when executed hits my API to grab results then redirects the user using

$location.url
. Everything works great...until I try to reload the results page. When I do so I get a
Cannot GET /search/[search-term]
message.

app.config.js:

'use strict';

angular.module('gameApp')
.config(function($routeProvider, $locationProvider) {
$routeProvider

.when('/player/:playerId', {
templateUrl: 'player.html'
})
.when('/search/:searchTerm', {
templateUrl: '/app/gmSearchResults/gmSearchResults.html'
});

$locationProvider.html5Mode({
enabled: true,
requireBase: false,
rewriteLinks: false
});
});


relevant navbar.controller.js:

vm.getSearchResults = function(searchTerm) {
searchService.resource.getResults({
query: searchTerm
}).$promise.then(function(results) {
if (results.playerId) {
$location.url('/customer/' + results.playerId);
} else {
saveLatest(results);
$location.url('/search/' + searchTerm);
}
});
};

Answer

Setup your express app:

app.route('/*').get(function(req, res) { 
    return res.sendFile(path.join(config.root, 'index.html')); 
});