Browse Source

update cors again

pearlgw 3 weeks ago
parent
commit
be95e876e0
1 changed files with 16 additions and 25 deletions
  1. 16 25
      index.ts

+ 16 - 25
index.ts

@@ -1,7 +1,7 @@
1 1
 import express, { Application, Request, Response } from 'express';
2
-import cors from 'cors';
3 2
 import path from 'path';
4 3
 import bodyParser from 'body-parser';
4
+import cors from 'cors';
5 5
 
6 6
 import { errorHandler } from './src/middleware/ErrorHandler';
7 7
 import keycloak from './src/middleware/Keycloak';
@@ -19,39 +19,30 @@ import './src/utils/Scheduler';
19 19
 
20 20
 const app: Application = express();
21 21
 
22
-const allowedOrigins = [
23
-    "http://localhost:3006",              // frontend local
24
-    "https://radar-dev.farmagitechs.co.id" // production domain
22
+const whitelist = [
23
+    "http://localhost:3006",
24
+    "https://radar-dev.farmagitechs.co.id"
25 25
 ];
26 26
 
27
-const corsOptions = {
28
-    origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
29
-        if (!origin || allowedOrigins.includes(origin)) {
30
-            // allow requests tanpa Origin (misal Postman) & origin yg ada di daftar
31
-            callback(null, true);
27
+var corsOptions = {
28
+    origin: function (origin: any, callback: any) {
29
+        if (whitelist.indexOf(origin) !== -1) {
30
+            callback(null, true)
32 31
         } else {
33
-            callback(new Error("Not allowed by CORS"));
32
+            callback(new Error('Not allowed by CORS'))
34 33
         }
35
-    },
36
-    methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
37
-    allowedHeaders: ["Content-Type", "Authorization"],
38
-    credentials: true,
39
-};
34
+    }
35
+}
36
+
37
+// Pasang sekali aja global
38
+app.use(cors(corsOptions));
40 39
 
41
-// app.use(cors());
42
-app.use(cors({
43
-    origin: "*",
44
-    methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
45
-    allowedHeaders: ["Content-Type", "Authorization"]
46
-}));
47
-app.options(/(.*)/, cors(corsOptions));
48 40
 app.use(bodyParser.json());
49 41
 app.use(keycloak.middleware());
50
-app.use(express.json())
42
+app.use(express.json());
51 43
 app.use('/storage/', express.static(path.join(__dirname, 'storage/')));
52 44
 
53 45
 const apiV1 = express.Router();
54
-
55 46
 apiV1.use('/province', provinceRoutes);
56 47
 apiV1.use('/city', cityRoutes);
57 48
 apiV1.use('/hospital', hospitalRoutes);
@@ -69,4 +60,4 @@ app.use(errorHandler);
69 60
 
70 61
 app.listen(config.port, () => {
71 62
     console.log(`Server started on port ${config.port}`);
72
-})
63
+});