using express-device with sails

烂漫一生 提交于 2019-12-11 20:23:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!