MattDionis
MattDionis

Reputation: 3616

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);
    }
  });
};

Upvotes: 4

Views: 5444

Answers (2)

Just a small edit to Georgii Kats answer. Try using:

    app.get('/*', function (req, res, next) {
       if (/.js|.html|.css|templates|js|scripts/.test(req.path) || req.xhr) {
       return next({ status: 404, message: 'Not Found' });
       } else {
          return res.render('index');
       }
    });

Upvotes: 0

user1050438
user1050438

Reputation:

Setup your express app:

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

Upvotes: 7

Related Questions