Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs express middleware function return value

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 because NodeJS does not move over to the next function.

But I need the isMobile function to return a value so I can process accordingly in the app.get. Any ideas?

app.get('/', isMobile, function(req, res){  // do something based on isMobile return value });    function isMobile(req, res, next) {      var MobileDetect = require('mobile-detect');     md = new MobileDetect(req.headers['user-agent']);      //return md.phone(); // need this value back      return next(); } 

Thanks.

like image 401
user3658423 Avatar asked May 31 '14 02:05

user3658423


People also ask

What does Express function return?

The var app = express() statement creates a new express application for you. The createApplication function from the lib/express. js file is the default export, which we see as the express() function call. The app object returned from this function is one that we use in our application code.

What is Express () function?

Express provides methods to specify what function is called for a particular HTTP verb ( GET , POST , SET , etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response.

What is middleware function in Express js?

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc.

Can Express middleware be async?

In closing, utilizing async / await as your Express middleware implementation helps keep your code reusable, readable, and up-to-date with current coding conventions.


1 Answers

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;         }     } 
like image 197
Farid Nouri Neshat Avatar answered Sep 28 '22 08:09

Farid Nouri Neshat