【发布时间】:2013-02-18 20:08:39
【问题描述】:
我想制作一个带有 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*/);
许多工作示例(例如 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 进行处理。怎么说呢?
【问题讨论】:
-
我不是 Express 用户,但这个问题应该与任何 Angular 后端有关。如果您只是指示您的 Express 将所有内容路由到 root (localhost:3005),您应该打开 Angular 前端,然后 Angular 应该从那里获取相对路径并确定要打开哪个客户端路由。因此,如果用户请求 localhost:3005/1/foo,您的 Express 应该像收到对 localhost:3005 的请求一样提供 HTML。那时,一旦你的 HTML 加载了 Angular,Angular 就应该选择当前位置并确定要打开哪个客户端视图/ctrl。
-
找到解决方案了吗?
标签: html url express angularjs url-routing