sails route(1) -用户定义路由

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'}]

posted @ 2017-06-15 09:00  simadi  阅读(379)  评论(0编辑  收藏  举报