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

Time:06-06

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:

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

CodePudding user response:

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

CodePudding user response:

TL;DR yes, is the same

This cors() is from cors package.

CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

Basically is just a beautiful way to enable cors in routes with middleware.

You can check in source code to see how it works, and check documentation other usage ways

  • Related