2014-03-30 31 views

回答

3

无法实现自定义中间件,因此无法在Sails中的req.params.all()的结果中添加任何内容,因为它在请求时被解析并提供用于在任何用户级代码运行之前路由处理程序。但是,如果您正在查找的是默认参数选项,则在Sails v0.10.x中,可以使用req.options散列作为此参数。如果你想设置一个默认的限制蓝图“发现”,例如,你可以做以下的/config/routes.js

'/user': {blueprint: 'find', options: {limit: 10}} 

这些选项的说明文件即将出台,在此期间,您可以examine the source code,看看哪些蓝图选项可用。

对于默认PARAMS在您的自定义控制器动作,可以以类似的方式使用options

'/foo': {controller: 'FooController', action: 'bar', options: {abc: 123}} 

,并在你的操作代码,检查选项:

bar: function(req, res) { 

    var abc = req.param('abc') || req.options.abc; 

} 

这是最好与req.params.all混淆,因为您可以判断您使用的是用户提供的还是默认值。但如果你真的想直接改变参数,可以,你可以在​​做到这一点通过定制中间件:

customMiddleware: function(app) { 

    app.use(function(req, res, next) { 

     // Note: req.params doesn't exist yet because the router middleware 
     // hasn't run, but we can add whatever we want to req.query and it 
     // will stick as long as it isn't overwritten by a route param or 
     // something in req.body. This is the desired behavior. 
     req.query.foo = req.query.foo || 'bar'; 
     return next(); 

    }); 

} 
3

在任何情况下,可能需要这个。

我只是需要处理一个类似的问题,在流量到达控制器之前,我不得不将一部分URL从多种语言翻译成英文。

首先,我使用了Sails v0.10.5,我不知道这个过程会持续多久。

在此版本中,推荐添加中间件的方式是使用policyhttp配置。 起初,我尝试创建一个策略,但Sails不允许您更改策略中的参数。因此我使用了http。这种配置提供了为http请求添加自己的中间件的可能性。

在那里你会发现middleware:属性,你可以添加自己的功能,然后将其插入order数组:

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(); 
} 
1

在控制器,我想为一个数据库插入创建模型的新项目,等这一个对我的作品,例如:

var requestParams = req.params.all(); 
requestParams.newParameter = 'XYZ'; 
requestParams.whatever = '123'; 

而且使用requestParams对象,你需要的所有参数+附加参数。例如:

MyModel.create(requestParams, function(err, user) { 
    ... 
}); 
相关问题