我想做一个AngularJS应用程序与html5风格的URL(即没有#
片段在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*/);
很多像AngularFun这样的例子都不使用HTML5模式。对于像http://localhost:3005/#/1/foo
这样的请求,显然
-
http://localhost:3005/
部分由Express处理服务器端/
。Express很高兴地为我们启用了angular的index.html
服务 -
/1/foo
路由由Angular的路由器 处理。
假设我们的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模式,我们的URL http://localhost:3005/#/1/foo
变成http://localhost:3005/1/foo
(没有更多的哈希#
)。这一次,整个URL都被Express截获了,它会变得混乱,因为我们没有定义/
以外的路由。
我们真正想说的是,URL的后半部分(/1/foo
)应该被"委托"给Angular来处理。我们怎么能这么说呢?
看起来一切正常。然而,我自己并没有做这项工作。我依赖于这个骨架项目:https://github.com/thanh-nguyen/angular-express-seed-coffee
这允许您在一定程度上控制哪些路径由客户端处理,哪些路径由服务器处理。