Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between these 2 pieces of code for pre-flight in NodeJS Express

First of all, I am a beginner with NodeJS, I am just watching some tutorials to get my feet wet: this question will probably sound very silly to anyone who has any Node experience.

In short, I am trying to allow pre-flight requests on my server, and the docs suggest I do this before my routes:

app.use(cors());

app.options('*', cors());

The tutorial I am following, on the other hand, proposes this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

app.use(cors())

app.options("*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS");
  res.header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-Requested-With");
})

So, what is the difference between these 2 pieces of code?
My current hypothesis is that

app.options('*', cors());

and

res.header("Access-Control-Allow-Origin", "*");

are equivalent, but I am not sure

>Solution :

The second one allows you to set custom values for the allowed origin/methods/headers, but the CORS middleware actually supports this anyway – see the "Configuration Options" section on this page.

To explain a bit what’s going on here:

  • app.use(cors()) means "use the cors() middleware for all methods and all paths".
  • app.options('*', cors()) means "use the cors() middleware for the OPTIONS method, for all paths (*)".
  • app.options('*', (req, res, next) => { /* ... */ }) means "use the provided function as a middleware for all OPTIONS requests, for all paths (*)".
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading