Search code examples
javascriptnode.jsexpressmiddleware

How to access application-level middleware from router?


I am trying to access my application-level middleware from router in a project generated with express application generator.

Middleware is used to query database with user ID received from router.

I feel like I'm missing something very simple (or fundamental) but can't get around the problem (this being my first Node.js project). So more than best practice I'm looking for a simple solution

I've tried using different app methods including post.

/app.js

var MyAppMidW = function (req, res, next) {
  res.send(queryDB(req));
  next()
}
app.use(MyAppMidW);

/routes/index.js

router.get("/dbquery", (req, res) => {
  if (req.header('auth-header')) {
    res.send(req.app.get.MyAppMidW(req.header('auth-header'))); //The problem
  }
  else {
    res.send(req.app.get('defaultData')); //This works
  }
});

Error messages include "$middleware is not a function" and "$middleware is not defined".

Solution

/app.js

app.MyAppMidW = function (req) {
  queryDB(req);
}

/routes/index.js

router.get("/dbquery", (req, res) => {
  if (req.header('auth-header')) {
    req.app.MyAppMidW(req.header('auth-header'))); //Makes a database query
    res.send(req.app.get('defaultData')); //Fetches database query result
  }
  else {
    res.send(req.app.get('defaultData'));
  }
});

Solution

  • You need to call app.set("MyAppMidW", MyAppMidW) and then you can use get. Or do this inside the app.js file

    app.MyAppMidW = function (req, res, next) {
      res.send(queryDB(req));
      next()
    }
    

    Then call it by req.app.get('MyAppMidW')(req.header('auth-header')) or req.app.MyAppMidW(req.header('auth-header')) inside the routes file.

    But middleware is called automatically when you say app.use(MyAppMidW) the function is called by default on each request. So no need to call it explicitly inside the router function.