Angularjs ngRoute # 在 URL

Angularjs ngRoute # in URL

这是我的angularjs路由

app.config(function($routeProvider, $locationProvider) {
  $routeProvider.
    when('/home', {
      templateUrl: 'partials/home.html'
    }).
    otherwise({
      redirectTo: '/'
    });

  if (window.history && window.history.pushState) {
    $locationProvider.html5Mode({
      enabled: true,
      requireBase: false
    });
  }
});

这 link 按预期工作

<a href="/home">Home</a>

但是,当我直接在地址栏中键入 http://localhost:3000/home 时,我得到一个空白页面。知道为什么会这样吗?

键入 http://localhost:3000/#/home 重定向到 http://localhost:3000/home 并按预期工作。

Angular 使用 ngRoutes 在不离开页面的情况下进行导航。如果您的路线包含 # 符号后跟路线,那么您仍在同一页面上。 Angular 这样做是为了在视图之间具有持久变量。如果您重定向到 /home 而不是 #/home,那么您正在加载服务器上 /home 文件夹的静态路径,并且 Angular 将在新页面加载时重新加载,所有变量都将被清除。

html5Mode 中的

AngularJS 使用 html5 history routing 去掉 url 中的 #。只要您在网页中导航,这就有效。

浏览器请求了您的 index.html 一次(它设置了您的应用程序,尤其是 ngRoute),然后单击 <a href="/home">Home</a> 等。 不会引起请求 到服务器。相反,ngRoute 会查找路线,操纵 html5 历史记录并显示您点击的内容。

但是,您必须告诉执行 localhost:3000/home 请求的浏览器有人在 url 栏中键入他实际上想要 index.html(不是 home/index.html,不存在)。这意味着 您必须配置您的服务器 以支持 html5 历史路由。 $location 文档对此有很长的 post。

如果您使用 express

,这是您要添加的内容
// this must be the last middleware added to your express app
app.use(function(req, res) {
  res.sendFile('index.html'); // specify the path to your index.html here
});

如果您直接在地址栏中键入 /home,您是在向服务器请求 /home 路径中的文档,而您实际上想要 AngularJS 应用程序在根路径中加载 /home 路由。你需要配置你的服务器,将除根路径以外的任何请求都重定向到根路径,并在一个#之后传递指定的路径,例如,将/home重定向到#/home