问题
been trying to play with sails framework as planning to port my express app. The problem I got into was how to make express-device npm package to work with it. In express app I just require module like in this case var device = require('express-device') and then configure it in server.configure. Any help?
回答1:
Ok, so I found the solution... After running npm install express-device --save I had to create a express.js module inside of config/ dir and the content of module looks like this:
module.exports.express = {
customMiddleware: function (app) {
var device = require('express-device');
app.use(device.capture());
}
};
so now in each controller I can find the type of device that request is coming from if I need to:
index: function(req, res) {
device = req.device.type;
if(device == 'mobile') {
// do something different ;)
}
}
Maybe there's some more clever ways to do this but this works fine for me :)
回答2:
It took me a bit of looking at the Sails middleware documentation (http://sailsjs.org/documentation/concepts/middleware) to figure this out, but it ends up being a little easier than the previous answer.
In config/http.js
, you'll want to add the following bits of code:
module.exports.http = {
middleware: {
order: [
...
'expressDevice',
...
],
expressDevice: require('express-device').capture(),
}
}
This will get the same result as the previous answer of having req.device
available on every request.
来源:https://stackoverflow.com/questions/20436169/using-express-device-with-sails