Adding custom Express middleware like jQuery-File-Upload to Sails.js

I'm still having a hard time understanding how to add middleware to sails.js. I heard how to use policy.js, create custom policies, add to local.js, etc. So can someone please show me exactly how I would add jquery-file-upload-middleware to the sail application. thanks in advance

+7
source share
2 answers

This would be very difficult in previous versions of Sails because you did not have control over the order in which the special middleware was included. In version 10.10, this is just curious.

Note. The following will work with the beta version of Sails (v0.10.x) installed through npm install sails@beta .

Inserting your own custom middleware in Sails is as simple as adding a customMiddleware function to your config/express.js , which takes an app as an argument; you can app.use reach your heart. The disadvantage of this approach is that it does not give you control over the inclusion of middleware. It is noteworthy that it turned on after the body analyzer, which will not work for your business.

In the latest version of Sails, you can override all middleware loading by implementing the loadMiddleware method in /config/express.js . The arguments are app , defaultMiddleware (the set of middleware functions commonly used by Sails) and sails (reference to the global Sails object). First, consider a standard kernel implementation — you probably want to copy the same order. So in your /config/express.js you will 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... } 
+14
source share

In the case of sails.js and jQuery Uploading a file, I think you can replace sails bodyParser with jQuery file uploader post method, an idea from this thread:

nginx / sails.js: incomplete file download

below example works fine for me. sails js 0.10.5

 npm install blueimp-file-upload-expressjs --save npm install lodash --save 

uncomment and add lines to /config/http.js file:

 middleware: { cbodyParser: require('../cbodyParser')( { urls: [/\/uploads/]} ), order: [ 'startRequestTimer', 'cookieParser', 'session', 'myRequestLogger', 'cbodyParser', // intersept multipart requests 'bodyParser', 'handleBodyParserError', 'compress', 'methodOverride', 'poweredBy', '$custom', 'router', 'www', 'favicon', '404', '500' ] } 

new file in the root folder /cbodyParser.js :

 var _ = require('lodash'); var options = { tmpDir: __dirname + '/uploads/tmp', publicDir: __dirname + '/uploads', uploadDir: __dirname + '/uploads', uploadUrl: '/uploads/', maxPostSize: 11000000000, // 11 GB minFileSize: 1, maxFileSize: 10000000000, // 10 GB acceptFileTypes: /.+/i, inlineFileTypes: /\.(gif|jpe?g|png)$/i, imageTypes: /\.(gif|jpe?g|png)$/i, imageVersions: { width: 220, height: 220 }, accessControl: { allowOrigin: '*', allowMethods: 'POST', allowHeaders: 'Content-Type, Content-Range, Content-Disposition' }, nodeStatic: { cache: 3600 // seconds to cache served files } }; var uploader = require('blueimp-file-upload-expressjs')(options); function mime(req) { var str = req.headers['content-type'] || ''; return str.split(';')[0]; } // start jQuery file uploader here: function parseMultipart(req, res, next) { uploader.post(req, res, function (obj) { res.send(JSON.stringify(obj)); }); next(); } // check for post method in request function disable_parser(opts, req, res) { var matched = false; try { var method = null; try {method = req.method.toLowerCase();} catch(err){ /* */} if(method) { _(opts.urls).forEach(function(turl) { if (method === 'post' && req.url.match(turl)) { // console.log("matched"+ req.url); if(!matched) matched = true; };}); } } catch(err) { debug(err);/* pass */ } return matched; } // Start all stuff.. module.exports = function toParseHTTPBody(options) { options = options || {}; // NAME of anynonymous func IS IMPORTANT (same as the middleware in config) !!! return function cbodyParser(req, res, next) { if (disable_parser(options, req, res) && mime(req) == 'multipart/form-data') { // we found multipart request to /uploads, so we can use jQuery file uploader instead return parseMultipart(req, res, next); } else { return next(); } }; }; 
+3
source share

All Articles