1. 程式人生 > >sails route(1) -用戶定義路由

sails route(1) -用戶定義路由

log sre findall action syn 尋找 resp login proc

sails支持兩種類型的路由: custom(or "explicit") andautomatic(or "implicit").

先來看一下custom 即用戶定義路由吧,以下是學習筆記。

用戶定義路由

在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‘

}

},

語法規則:

1.每個路由都必須包含地址和目標

‘GET /foo/bar‘:‘FooController.bar‘

^^^address^^^^^^^^^^target^^^^^^^

2.地址定義:

a.使用通配符和動態參數

比如:

‘/user/foo/*‘

‘/user/foo/:name/bar/:age‘

‘/user/foo/*/bar/*‘

b.正則表達式

"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中的書寫順序進行匹配,一旦匹配成功,便不會再往下繼續尋找(有高級的方法可以改變該規則,但不推薦)

3.路由目標定義

a. controller/action的語法規則:

‘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目標的語法規則:

‘GET /team‘: {view:‘brochure/about‘}

c. Blueprint目標的語法規則

‘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,即在達到指定target時,必須先通過某個policy

‘/foo‘: [{policy:‘myPolicy‘}, {blueprint:‘find‘, model:‘user‘}]

sails route(1) -用戶定義路由