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'}]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)