AngularJS html5Mode刷新失败

AngularJS html5Mode refresh fails

本文关键字:失败 刷新 html5Mode AngularJS      更新时间:2023-09-26

这是我的路由器:

var app = angular.module('tradePlace', ['ngRoute', 'tradeCntrls']);
app.config(['$routeProvider', '$locationProvider', function($route, $location) {
    $route.
    when('/', {
        redirectTo: '/index'
    }).
    when('/index', {
        templateUrl: './includes/templates/index.php',
        controller: 'indexCntrl'
    }).
    when('/register', {
        templateUrl: './includes/templates/register.php',
        controller: 'indexCntrl'
    }).
    otherwise({
        redirectTo: '/index'
    });
    $location.html5Mode(true);
}])

我将html5模式设置为true,所以现在URL中没有#。

如果我去mysite.com/它重定向我到/index,但当我重新加载页面(f5)或去mysite.com/index我得到一个404错误。

有办法解决这个问题吗?或者干脆不使用html5模式?

如果不从服务器上运行项目并做一些特殊的工作来路由请求,就没有办法解决这个问题。它包括以下步骤:

  1. 捕获静态文件请求(例如图像文件)
  2. 将其他请求发送到index.html,由路由器处理

例如,使用nodeJS express服务器,它看起来像这样:

// Capture real static file requests
app.use(express.static(__dirname + '/public'));
// All get requests not captured above go to the client.
server.get('*', function (req, res) {
    res.sendfile(__dirname + '/public/index.html');
});

注意,这不是Angular特有的问题。对于任何使用html5 pushState的客户端应用程序,都必须执行相同的步骤。

Apache在你的。htaccess中使用:

RewriteEngine On
RewriteBase /
RewriteRule ^index.php - [L]
#your static data in the folder app
RewriteRule ^app - [L]
#everything else
RewriteRule ^(.*)$ index.php?para=$1 [QSA,L]
编辑:

整个请求的url作为参数传递给php文件。如果需要,您可以在php脚本中使用$_GET['para']进一步处理此操作。

Apache会重写你的请求,并传递符合规则的文件。

。要求:

  • http://somehost.com/blabla -> index.php?帕拉=鼓励性
  • http://somehost.com/app/mainapp.js -> app/mainapp.js

将此添加到。htacces或。conf中模块目录AllowOverride所有通常为无