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
>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 thecors()middleware for all methods and all paths".app.options('*', cors())means "use thecors()middleware for theOPTIONSmethod, for all paths (*)".app.options('*', (req, res, next) => { /* ... */ })means "use the provided function as a middleware for allOPTIONSrequests, for all paths (*)".