From bfcd5c59eef896e9509ae2d293cb04c13ca75257 Mon Sep 17 00:00:00 2001 From: Bakhshi Moeez <107806938+BakhshiMoeez@users.noreply.github.com> Date: Sun, 16 Apr 2023 06:27:01 +0500 Subject: [PATCH] Update index.js Adding proper error message incase of invalid or undesired domain reaching out for our API in configuring CORS. --- index.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/index.js b/index.js index 5116dc331..3ea6ef68a 100644 --- a/index.js +++ b/index.js @@ -45,7 +45,21 @@ const db = { const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); -app.use(cors({ origin: /http:\/\/(127(\.\d){3}|localhost)/})); + +// ---------------------------------------------------- +const whiteList = [/http:\/\/(127(\.\d){3}|localhost)/]; +const corsOptions = { + origin: function (origin, callback) { + if (!origin || whiteList.some(regexp => regexp.test(origin))) { + callback(null, true); + } else { + callback(new Error("Not allowed by CORS")); + } + }, +}; + +app.use(cors(corsOptions)); +// ---------------------------------------------------- app.options('*', cors()); // ***************************************************************************