万一有人需要这个。
我只需要处理一个类似的问题,在流程到达控制器之前,我必须将 URL 的某些部分从多种语言翻译为英语。
首先,我使用的是 Sails v0.10.5,我不知道这要追溯到多久以前。
在此版本中,添加中间件的推荐方法是使用policy
or the http
配置。
起初,我尝试创建策略,但 Sails 不允许您更改策略内的参数。因此我诉诸于http
。此配置提供了为 http 请求添加您自己的中间件的可能性。
在那里你会发现middleware:
属性,您可以添加自己的函数,然后将其插入到order
array:
order: [
'startRequestTimer',
'cookieParser',
'session',
'myRequestLogger',
'bodyParser',
'handleBodyParserError',
'compress',
'methodOverride',
'poweredBy',
'$custom',
'__your_function',
'router',
'www',
'favicon',
'404',
'500'
]
所以我添加了自己的函数来订阅router:route
事件,以便 params 数组已填充。
addRouterListener: function (req, res, next) {
sails.on('router:route', function (args) {
// Proceed to changing your params here
// It would also be wise to check the route or the controller
if (args.options.controller === 'x' && args.req.params['type']){
args.req.params['type'] = translation[args.req.params['type']];
}
});
return next();
}