Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
usage of cors middleware vs custom middleware

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'})
})
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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().

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!