Home > Back-end >  usage of cors middleware vs custom middleware
usage of cors middleware vs custom middleware

Time:06-25

Pardon me for this stupid question, but can someone explain me how the cors middleware work?

I accidentally called an auth middleware by adding brackets after it and it ran that middleware without even me requesting to that route.

I know that adding brackets after function invokes it but what is it with cors middleware that we add those brackets after it??

usage of cors middleware from docs:

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

using auth middleware with () gives error:

app.get('/products/:id', auth(), function (req, res, next) {
  res.json({msg: 'This is an authorized Route'})
})

usage of auth middleware without () works fine:

app.get('/products/:id', auth, function (req, res, next) {
  res.json({msg: 'This is an authorized Route'})
})

CodePudding user response:

Functions can return other functions, when you call the cors function using cors(), you get back a new function, that is used as the middleware function in app.get(). Your cors() example could be rewritten like so:

const corsMiddlewareFn = cors();
app.get('/products/:id', corsMiddlewareFn, function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

Above we store the function that calling cors() returns in a variable called corsMiddlewareFn, and then we use that as middleware as part of the call to app.get(). Having cors() return a function is useful as it allows us to pass options to the cors() function so that the middleware function it returns can use those options accordingly.

On the other hand, your auth function most likely doesn't return a function, so auth itself is the middleware function you want to use, and not its return value which you would get when calling auth().

CodePudding user response:

The cors module returns a function that takes optional configuration and returns the middleware.

The auth is already the middleware, not a function, so no need to call it.

  • Related