-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathtest-cors.js
More file actions
63 lines (53 loc) · 1.89 KB
/
test-cors.js
File metadata and controls
63 lines (53 loc) · 1.89 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const http = require('http');
const options = {
hostname: 'localhost',
port: 3000,
path: '/health',
method: 'GET',
headers: {
'Origin': 'http://localhost:3000'
}
};
function checkCors(origin, expectedStatus, expectedAllowOrigin) {
return new Promise((resolve, reject) => {
const reqOptions = { ...options, headers: { 'Origin': origin } };
const req = http.request(reqOptions, (res) => {
const allowOrigin = res.headers['access-control-allow-origin'];
console.log(`Origin: ${origin}, Status: ${res.statusCode}, Access-Control-Allow-Origin: ${allowOrigin}`);
if (expectedAllowOrigin) {
if (allowOrigin === expectedAllowOrigin) {
resolve(true);
} else {
reject(new Error(`Expected ${expectedAllowOrigin}, got ${allowOrigin}`));
}
} else {
if (!allowOrigin) {
resolve(true);
} else {
reject(new Error(`Expected no Access-Control-Allow-Origin, got ${allowOrigin}`));
}
}
});
req.on('error', (e) => {
reject(e);
});
req.end();
});
}
async function runTests() {
try {
console.log('Testing Allowed Origin 1: http://localhost:3000');
await checkCors('http://localhost:3000', 200, 'http://localhost:3000');
console.log('Testing Allowed Origin 2: https://tradeflow-web.vercel.app');
await checkCors('https://tradeflow-web.vercel.app', 200, 'https://tradeflow-web.vercel.app');
console.log('Testing Disallowed Origin: http://evil.com');
await checkCors('http://evil.com', 200, undefined); // Should not return the header
console.log('All CORS tests passed!');
} catch (error) {
console.error('CORS Test Failed:', error.message);
process.exit(1);
}
}
// Give server a moment to start if needed, but this script assumes it's running.
// If run via a command that starts server then runs this, we need a wait.
runTests();