Add express middleware for param validations

天大地大妈咪最大 提交于 2019-12-09 10:55:12

问题


In a sails.js application is there a simple way of including express-middleware?

For instance extending the request object with express-validator.


回答1:


Adding express-middleware in a sails application is simple.

create a new policy.

policies
  |_
    middleware.js / .coffee

Add Express MiddlewareYOUR_MIDDLE_WARE_FILE_NAME.js

Inside your middleware file we create the standard export for node.js

module.exports = require('middle-ware')(OPTIONS_GO_HERE) // See middleware docs for configuration settings.

Then once you have created the middleware you can apply it to all requests or a single controller by following the Sails.js convension.

Entire Applicationpolicies.js

module.exports.policies = {
   '*':['middleware'] // node same name as file without extention
}

Single Controller Action policies.js

module.exports.policies = {
   RabbitController:{
      feed:['middleware']
   }
}



回答2:


First of all, @SkyTecLabs' answer is the proper way to do this. But I wanted to add that, in some cases, you may need to control your static files (images, client-side javascript, css, etc) as well (I just had to deal with this recently). In this case, you can apply middleware generically to every route.

As of Sails.js v0.9.3, you can do:

// Put this in `config/express.js`
module.exports.express = {
  customMiddleware: function (app) {
    app.use(require('../node_modules/sails/node_modules/express').basicAuth('balderdash', 'wickywocky'));
  }
};

More here: https://gist.github.com/mikermcneil/6255295

In the case where you want middleware to run before one or more of your controllers or actions, you're definitely better served using the policy approach though!



来源:https://stackoverflow.com/questions/18215906/add-express-middleware-for-param-validations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!