-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcors.js
45 lines (41 loc) · 1.38 KB
/
cors.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const cors = require('cors');
const express = require('express');
//white list the sources
const whiteList = [ "http://localhost:3000" ];
// set Origin header as source e.g. "http://localhost:3000/"
let corsOptionsDelegate = function (req, callback) {
let corsOptions;
console.log("Origin : ", req.header('Origin'));
if (whiteList.includes(req.header('Origin'))) {
console.log("Yes origin accepted");
corsOptions = { origin: true };
}
else {
console.log("Origin not accepted");
corsOptions = { origin: false };
}
callback(null, corsOptions);
};
// set Origin header as source e.g. "http://localhost:3000/"
// Use the following middleware function to verify cors
function checkCorsValidity (req, res, next) {
let myorigin = req.header('Origin');
if (myorigin.lastIndexOf('/') === (myorigin.length-1)) {
myorigin = myorigin.slice(0,myorigin.length-1);
}
console.log("Origin : ", myorigin);
if (whiteList.includes(myorigin)) {
console.log("Yes origin accepted");
next();
}
else {
console.log("Origin not accepted");
let err = new Error("This source is not recognized!");
err.status = 403;
next(err);
}
// callback(null, corsOptions);
};
exports.cors = cors();
exports.corsWithOptions = cors(corsOptionsDelegate);
exports.checkCorsValidity = checkCorsValidity;