【问题标题】:AngularJS html5Mode refresh failsAngularJS html5Mode 刷新失败
【发布时间】:2014-07-09 14:44:54
【问题描述】:

这是我的路由器:

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模式?

【问题讨论】:

    标签: javascript html angularjs


    【解决方案1】:

    如果不从服务器运行您的项目并做一些特殊的工作来路由请求,则无法解决此问题。它涉及以下步骤:

    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 的客户端应用程序都必须执行相同的步骤。

    【讨论】:

    • 有.htaccess 解决方案吗?
    • @user3144435 是的,有。我给你一个
    【解决方案2】:

    供 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 文件。如果需要,您可以使用 $_GET['para'] 在 php 脚本中进一步处理。

    Apache 重写您的请求并交付符合规则的文件。

    即请求:

    【讨论】:

    • 工作,谢谢。所以 AngularJS 读取 'para'。你在哪里找到的?
    • 不,AngularJS 不读取段落。 para 作为参数传递给文件。如果你有一个 php 脚本,你可以使用 $_GET 从 para 读取值。我会修正我的答案。
    【解决方案3】:

    在 .htacces 或 .conf 中添加这个 在模块目录上 允许覆盖所有 通常是无

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-18
      • 1970-01-01
      • 2015-07-31
      • 2015-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 2015-08-21
      相关资源
      最近更新 更多