【问题标题】:AngularJS: 404 on page refresh, clean urls, using $locationProvider.html5ModeAngularJS:页面刷新时 404,干净的 url,使用 $locationProvider.html5Mode
【发布时间】:2016-12-11 10:59:54
【问题描述】:

我正在尝试使用 $locationProvider.html5Mode(true); 解决此问题;刷新页面时。

它修复了 URL 中的这个 localhost/#/home 哈希,但是当我刷新页面时它显示 404。

我正在使用nginx local

正在运行angularjs v1.0.7。最新版本显然不起作用。

标题

<base href="/">

角度

var app = angular.module('myApp', []);

app.config(function($routeProvider, $locationProvider) {
      $routeProvider
      .when('/', {
        templateUrl: 'home.html',
        title: 'home'
      })
      .when('/about', {
        templateUrl: 'about.html',
        title: 'about'
      })
      .when('/contact', {
        templateUrl: 'contact.html',
        title: 'contact'
      })
      .otherwise({
        redirectTo: '/'
      });
      $locationProvider.html5Mode(true);
    });

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    当您使用 Html5 模式时,您的链接会从 http://example.com/#about 变为 http://example.com/about,但您收到 404 的原因有一个 - 您使用什么服务器端解决方案?由于您的 404 是由您的后端而不是由 angularJS 路由器本身返回的,为了使其在 html5 模式下可访问,您需要在服务器端的新路由中提供包含 js 的相同 html 页面,就像您提供给您的家一样页面加载您的角度应用程序。 例如,在 Laravel 中,假设您的站点根目录有这样的路由,并且您的 Angular 应用程序代码位于 home.blade.php

        Route::get('/',function(){ return view('home');});
    

    因此,您需要创建指向相同视图的相同路由,以便使用标记加载您的 Angular js 应用程序,然后您的 Angular 路由器将根据路由视图正确显示您所需的模板。

       Route::get('/about',function(){ return view('home');});
       Route::get('/contact',function(){ return view('home');});
    

    如果您使用不同的服务器端框架或解决方案,希望您对直接访问时需要做什么来解决 404 问题有一个主要的想法 - 只需在服务器端设置相同的路由,指向加载您的 Angular js 应用程序的主页。 如果您不使用任何通过 nginx 提供静态 html 文件的服务器端框架,则需要设置 /contacts /about 位置以指向包含您的 Angular 应用程序的文档根 index.html。

    举例

    location / {
        root   /srv/www/example.com/public_html;
        index  index.html index.htm;
    }
    location /about/ {
        root   /srv/www/example.com/public_html;
        index  index.html index.htm;
    }
    location /contacts/ {
        root   /srv/www/example.com/public_html;
        index  index.html index.htm;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 2019-04-30
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      相关资源
      最近更新 更多