nodejs express middleware function return value

后端 未结 1 530
长发绾君心
长发绾君心 2021-02-02 12:23

I\'m using NodeJS and Express, I have the following route and the middleware function isMobile. If I don\'t use return next(); in the isMobile function, the app gets stuck becau

1条回答
  •  佛祖请我去吃肉
    2021-02-02 12:38

    You have a couple of choices:

    1. Attach the value to the req object:

      app.get('/', isMobile, function(req, res){
         // Now in here req.phone is md.phone. You can use it:
         req.phone.makePrankCall();
      });
      
      function isMobile(req, res, next) {
          var MobileDetect = require('mobile-detect');
          md = new MobileDetect(req.headers['user-agent']);
      
          req.phone = md.phone();
          next();// No need to return anything.
      }
      

      This is how many of express/connect middlewares pass values. Like bodyParser which attaches body property to request object, or session middleware which attaches session property to request object.

    Though note that you have to be careful that no other library uses that property, so there's no conflicts.

    1. Don't make it a middleware, just use the function directly. If it's not asynchronous like above, and not gonna be used globally for all routes(not gonna have something like this: app.use(isMobile)), this also a good solution:

      app.get('/', function(req, res){
         var phone = isMobile(req);
         phone.makePrankCall();
      });
      
      function isMobile(req) {
          var MobileDetect = require('mobile-detect');
          md = new MobileDetect(req.headers['user-agent']);
      
          return md.phone();
      }
      

    If it's expensive to compute, and you might use it in more than one middleware you can cache it with a WeakMap(or use a module that does it for you):

        app.get('/', function(req, res){
           var phone = isMobile(req);
           phone.makePrankCall();
        });
    
        var cache = new WeakMap()
    
        function isMobile(req) {
            var MobileDetect = require('mobile-detect');
    
            result = cache.get(req);
    
            if (result) {
                return result;
            } else {
                md = new MobileDetect(req.headers['user-agent']).phone();
                cache.set(req, md);
                return md;
            }
        }
    

    0 讨论(0)
提交回复
热议问题