I'm still having difficulty understanding how to add middleware to sails.js. I've heard use policies.js, create custom policies, add to local.js, etc. So could someone please show me how exactly I would add the jquery-file-upload-middleware to a sails app. Thanks in advance
This would have been very difficult in previous versions of Sails, because you had no control over the order in which custom middleware was included. In v0.10, it's just kinda difficult.
Note: the following will work with the beta version of Sails (v0.10.x), installable via npm install sails@beta
.
Inserting your own custom middleware into Sails is as easy as adding a customMiddleware
function to your config/express.js
file which takes app
as an argument; you can then app.use
to your heart's content. The downside with this approach is that it doesn't give you control over when your middleware is included. Notably, it's included after the body parser, which won't work for your case.
In the newest version of Sails, you can override all of the middleware loading by implementing a loadMiddleware
method in /config/express.js
. The arguments are app
, defaultMiddleware
(the set of middleware functions that Sails usually includes by default), and sails
(a reference to the global Sails object). Take a look at the default core implementation first--you'll probably want to copy the same order. So in your /config/express.js
, you'd have something like:
var upload = require('jquery-file-upload-middleware');
// configure upload middleware
upload.configure({
uploadDir: __dirname + '/public/uploads',
uploadUrl: '/uploads',
imageVersions: {
thumbnail: {
width: 80,
height: 80
}
}
});
module.exports.express = {
loadMiddleware: function(app, defaultMiddleware, sails) {
// Use the middleware in the correct order
app.use(defaultMiddleware.startRequestTimer);
app.use(defaultMiddleware.cookieParser);
app.use(defaultMiddleware.session);
// Insert upload file handler
app.use('/upload', upload.fileHandler());
app.use(defaultMiddleware.bodyParser);
app.use(defaultMiddleware.handleBodyParserError);
app.use(defaultMiddleware.methodOverride);
app.use(defaultMiddleware.poweredBy);
app.use(defaultMiddleware.router);
app.use(defaultMiddleware.www);
app.use(defaultMiddleware.favicon);
app.use(defaultMiddleware[404]);
app.use(defaultMiddleware[500]);
}
...etc...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With