-
Notifications
You must be signed in to change notification settings - Fork 215
07. Mojito v0.9: Using Middleware
In Mojito v0.9, your applications have to explicitly request Mojito middleware in app.js
. You can request all of the Mojito middleware or select certain modules of the Mojito middleware. To use you own middleware, you no longer use the middleware
property in application.json
to specify the directory that holds the middleware. Instead, you write middleware for Mojito applications just as you would for an Express application. We're going to cover all three use cases in the following sections:
Your app.js
can access all of Mojito's middleware using the Express method app.use
with the argument
libmojito.middleware()
, where libmojito
is an instance of Mojito as shown in the code below:
var express = require('express'),
libmojito = require('mojito'),
app;
app = express();
libmojito.extend(app);
app.use(libmojito.middleware());
You also have more control about what Mojito middleware to include in your application. You can select the desired middleware by passing the module name of the middleware as shown in this example:
var express = require('express'),
libmojito = require('mojito'),
app;
app = express();
libmojito.extend(app);
app.use(libmojito.middleware['mojito-handler-static']());
app.use(libmojito.middleware['mojito-parser-body']());
app.use(libmojito.middleware['mojito-parser-cookies']());
app.use(libmojito.middleware['mojito-contextualizer']());
app.use(libmojito.middleware['mojito-handler-tunnel']());
Writing middleware for Mojito application is virtually the same now for Mojito applications. You can have the middleware in the app.js
file or require an external file in app.js
.
For instance, you could just leverage Express middleware in your app.js
as we're doing here with the authBasic
middleware:
var express = require('express'),
libmojito = require('mojito'),
app;
app = express();
libmojito.extend(app);
app.use(express.basicAuth(function(user, pass){
return 'yahoo' == user && 'next' == pass;
}));
You could also create the file mymiddleware.js
with the following:
var express = require('express');
module.exports = function() {
return express.basicAuth(function(user, pass){
return 'mojito' == user && 'next' == pass;
});
};
And then include it in app.js
:
var express = require('express'),
libmojito = require('mojito'),
myMiddleware = require('./mymiddleware'),
app = = express();
app.set('port', process.env.PORT || 8666);
libmojito.extend(app);
app.use(myMiddleware());