Home > Blockchain >  How does a method work as callback in app.use()?
How does a method work as callback in app.use()?

Time:09-22

Normally, a function is passed as callback in app.use(), like so:

const express = require('express');
const app = express();

app.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

In the case of node-expose-sspi however a method is passed:

const express = require('express');
const { sso } = require('node-expose-sspi');

const app = express();
app.use(sso.auth()); //stores something in req.sso

app.use((req, res, next) => {
  res.json({
    sso: req.sso,
  });
});

Why is the method passed with ()? If it uses () why is it no called immediately (without arguments)?
Also, how can I wrap a method in a callback function, e.g.

app.use(myCallback);

function myCallback(req, res, next) {
  sso.auth(); //req.sso is undefined
}

CodePudding user response:

app.use(sso.auth());

calls sso.auth() and app.use()s its return value.

You can find over here in the node-expose-sspi source that .auth() indeed returns a new middleware function.

As for the second question

Also, how can I wrap a method in a callback function

you shouldn't do that – Express will call your used middlewares in order; a subsequent callback will have access to whatever a previous middleware has injected into the request.

If you for some reason really need to do that,

const ssoAuth = sso.auth();

function myCallback(req, res, next) {
  ssoAuth(req, res, () => {
    // whatever would regularly be in `myCallback`
    next();
  });
}
``
  • Related