我想制作一个带有 HTML5 样式 URL 的 AngularJS 应用程序(即没有#
URL 中的片段)。因此,在我的 Angular 应用程序的路由控制器模块中,我有如下内容:
angular.module('app').config(['$routeProvider','$locationProvider',function($routeProvider,$locationProvider) {
$locationProvider.html5Mode(true)
...
}
$routeProvider
.when('/1/:param', /* do something */)
.when('/2/:param', /* do something else */)
.when('/3/:param', /* do something else again*/);
许多工作示例,例如角趣 https://github.com/CaryLandholt/AngularFun不要使用 HTML5 模式。对于像这样的请求http://localhost:3005/#/1/foo
,很明显
- the
http://localhost:3005/
部分由服务器端处理/
通过快递。 Express 很乐意为我们支持 Angular 的服务提供服务index.html
- the
/1/foo
路由由 Angular 的路由器在客户端处理
Say our server.coffee
作为标准,看起来像下面这样(我们提供静态dist
包含我们编译的、缩小的 Angular 源代码的目录:
express = require 'express'
routes = require './routes'
dir = "#{__dirname}/dist" # sources live here
port = process.env.PORT ? process.argv.splice(2)[0] ? 3005
app = express()
app.configure ->
app.use express.logger 'dev'
app.use express.bodyParser()
app.use express.methodOverride()
app.use express.errorHandler()
app.use express.static dir # serve the dist directory
app.use app.router
routes app, dir # extra custom routes
如果我们确实使用 HTML5 模式,我们的 URLhttp://localhost:3005/#/1/foo
变成http://localhost:3005/1/foo
(不再有哈希#
)。这次,整个 URL 被 Express 拦截,它会变得混乱,因为我们没有定义除/
.
我们真正想说的是 URL 的后半部分(/1/foo
)应该“委托”给 Angular 来处理。我们怎么说呢?