前段時間學(xué)習(xí)了一下sails继谚,node下面一個mvc的web application框架走贪,它的思路借鑒了rails(ruby)。
sails支持兩種類型的路由:?custom(or "explicit") andautomatic(or "implicit").
先來看一下custom 即用戶定義路由吧,以下是學(xué)習(xí)筆記腻窒。
用戶定義路由
在config/routes.js中定義如下類似的路由:
module.exports.routes={
'get/signup': { view: 'conversion/signup' },
'post /signup':'AuthController.processSignup',
'get/login': { view: 'portal/login' },
'post /login':'AuthController.processLogin',
'/logout':'AuthController.logout',
'get /me':'UserController.profile'
}
有的將url指向某個controller的action滩字,有的則將url指向某個view
甚至還可以在路由中指定view使用的layout
'get /privacy': {
view:'users/privacy',
locals: {
layout:'users'
}
},
語法規(guī)則:
1.每個路由都必須包含地址和目標(biāo)
'GET /foo/bar':'FooController.bar'
^^^address^^^^^^^^^^target^^^^^^^
2.地址定義:
a.使用通配符和動態(tài)參數(shù)
比如:
'/user/foo/*'
'/user/foo/:name/bar/:age'
'/user/foo/*/bar/*'
b.正則表達(dá)式
"r||
list of param names>"
比如:
"r|^/\\d+/(\\w+)/(\\w+)$|foo,bar":"MessageController.myaction"
Will
match/123/abc/def, running themyactionaction ofMessageControllerand supplying the valuesabcanddefasreq.param('foo')andreq.param('bar')
c.路由地址匹配的順序
按照routes.js中的書寫順序進(jìn)行匹配造虏,一旦匹配成功御吞,便不會再往下繼續(xù)尋找(有高級的方法可以改變該規(guī)則,但不推薦)
3.路由目標(biāo)定義
a. controller/action的語法規(guī)則:
'GET /foo/go':'FooController.myGoAction',
'GET /foo/go':'Foo.myGoAction',
'GET /foo/go': {controller:"Foo", action:"myGoAction"},
'GET /foo/go': {controller:"FooController", action:"myGoAction"},
以上四種寫法等價漓藕。
需要注意的是陶珠,controller和action的名字是大小寫敏感的。
b.view目標(biāo)的語法規(guī)則:
'GET /team': {view:'brochure/about'}
c. Blueprint目標(biāo)的語法規(guī)則
'GET /findAllUsers': {model:'user', blueprint:'find'},
'GET /user/findAll': {blueprint:'find'}
'GET /user/findAll': {blueprint:'find', model:'pet'}
4.定義重定向(redirect)
'/alias' :'/some/other/route'
'GET /google':'http://www.google.com'
5.定義response
'/foo': {response:'notFound'}
6.function定義
路由可以直接指向某個function
'/foo':function(req, res) {res.send("FOO!");}
7.Policy target syntax
路由可以為target指定policy享钞,即在達(dá)到指定target時揍诽,必須先通過某個policy
'/foo': [{policy:'myPolicy'}, {blueprint:'find', model:'user'}]