Angular '不能GET'路由页面刷新

Angular 'Cannot GET' route on page refresh

本文关键字:刷新 不能 Angular GET 路由      更新时间:2023-09-26

在我的Angular应用程序中有一个搜索函数,当它执行时,它会点击我的API来获取结果,然后使用$location.url重定向用户。一切都很好……直到我尝试重新加载结果页面。当我这样做时,我得到一个Cannot GET /search/[search-term]消息。

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

设置express应用程序:

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

对Georgii Kats的回答做一个小小的修改。尝试使用:

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