如何在 Nodejs + AngularJS 解决方案中启用地址栏的深度链接

How do I enable deep linking from address bar in a Nodejs + AngularJS solution

所以我设置了一个简单的 NodeJS + ExpressJS 服务器,负责为 AngularJS 应用程序路由和传送内容。它工作正常并且路由有效,但只能在应用程序内使用。如果我在地址栏中键入任何内容,home.html 就会得到服务——这是有道理的,因为我定义(在 Node 中进行路由)除部分之外的任何内容都应该服务 home.html。

但是我该如何深入 link 工作呢?

当我输入 localhost:3000/registrations 时,系统会提供 localhost:3000/forms。但是,如果我在页面上创建 link 并在 localhost:3000/registrations 中创建 link,它就可以工作。另外,如果我在地址栏中输入 localhost:3000/registrations localhost:3000/forms is served.

NodeJS+Express 服务器

var express = require('express');
var app = express();

//Set up static directory for serving static html
app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
  res.sendFile(__dirname + '/views/home.html');
});

app.get('/partials/:name', function (req, res) {
  var name = req.params.name;
  res.sendFile(__dirname + '/views/partials/' + name);
});

app.get('*', function(req, res) {
  res.redirect('/');
});

//Start server
app.listen(3000);
console.log('Server startet on port 3000');

AngularJS 应用程序和控制器 - app.js

var app = angular.module('regApp', [
  'ngRoute'
])
.config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider.
    when('/form/:id', {
        templateUrl: 'partials/form.html',
        controller: 'FormCtrl'
      }).
    when('/forms', {
        templateUrl: 'partials/forms.html',
        controller: 'FormsCtrl'
      }).
    when('/registrations', {
        templateUrl: 'partials/registrations.html',
        controller: 'GridCtrl'
      }).
    otherwise( { redirectTo: "/forms" });
  }]);

主要html - home.html

<!DOCTYPE html>
<html ng-app="regApp">
<head lang="en">
  <meta charset="UTF-8">
  <base href='/'>
  <title>Registration app</title>
</head>
<body>
  <div class="jumbotron text-center">
    <h1>RegistrationApp</h1>
  </div>

  <div class="container">
    <div ng-view></div>
  </div>

  <script src="/vendor/angular/angular.min.js"></script>
  <script src="/vendor/angular-route/angular-route.min.js"></script>
  <script src="/js/app.js"></script>

</body>
</html>

确保直接路由时指向 index.html 文件。 #/registration 与 /registration.

进一步说明。 #/registration 与 /registration 不同 link。 #/registration 实际上是一个锚 link 作为路由传递给 angular,其中 /registration 会尝试路由到名为 /registration 的子目录。如果您愿意,可以创建该目录并构建一个新的 angular 应用程序,该应用程序专门用于注册新用户。