using express-device with sails

2019-09-16 03:02发布

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?

2条回答
Juvenile、少年°
2楼-- · 2019-09-16 03:43

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.

查看更多
Evening l夕情丶
3楼-- · 2019-09-16 03:51

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 :)

查看更多
登录 后发表回答