Add Express Middleware to Verify Settings

Is there an easy way in sails.js application to enable express-middleware ?

For example, extending a query object with express-validator .

+7
source share
2 answers

Adding express middleware to the sails application is simple.

create a new policy.

 policies |_ middleware.js / .coffee 

Add Express Middleware YOUR_MIDDLE_WARE_FILE_NAME.js

Inside your intermediate file, we create a 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 to one controller, following the Sails.js content.

Integrated policies.js application

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

The action of one controller policies.js

 module.exports.policies = { RabbitController:{ feed:['middleware'] } } 
+11
source share

First of all, @SkyTecLabs answer is the right way to do this. But I would like to add that in some cases, you may need to also manage your static files (images, client-side javascript, css, etc.) (I just had to deal with this lately). In this case, you can use middleware in general for each route.

As in 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 details here: https://gist.github.com/mikermcneil/6255295

If you want middleware to run before one or more of your controllers or actions, you are definitely better off using a political approach though!

+7
source share

All Articles