Comparing/Implementing `app.use(cors(corsOptions));` and `app.options('*', cors(corsOptions));` in Express/Node Application

Viewed 1094

I am new to implementing CORS(enabling it for everyone) in a Node/Express application. I have found a snippet of code in app.js which is mentioned below:

const express = require('express');
const corsOptions = {
  origin: '*',
};
const app = express();
app.use(cors(corsOptions));
app.options('*', cors(corsOptions));
app.listen(config.PORT);

I found the last two lines of code to be redundant. I am not sure as I am unable to test the CORS right now due to limited knowledge/understanding and resources on running Node/Express project.

Is it sufficient if we mention either app.use(cors(corsOptions)); or
app.options('*', cors(corsOptions));?
If Yes, is there a difference in their implementation?
If No, how does each line of code configure the Express Application?

1 Answers

Yes, the options() will do the exact the same but only for the request path * and http OPTIONS requests.

The use() will not care about the verb of the request, but can have a request path as first argument if needed.

Related