-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy-server-as-serverless.js
89 lines (77 loc) · 2.77 KB
/
proxy-server-as-serverless.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// api/proxy.js
const fetch = require('node-fetch');
const https = require('https');
const cookieParser = require('cookie-parser');
const { red, green, yellow, blue, magenta, cyan } = require('colorette');
// Initialize middleware-like functions
const bodyParser = require('body-parser');
const cors = require('cors');
const allowedOrigins = ['http://localhost:4200', 'http://MY_UI_ADDRESS.com'];
const agent = new https.Agent({
rejectUnauthorized: false,
});
module.exports = (req, res) => {
// Apply CORS middleware
cors({
origin: function (origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
})(req, res, () => {
// Parse cookies
cookieParser()(req, res, () => {
// Parse body
bodyParser.json()(req, res, async () => {
// Handle the request
if (req.method === 'POST' && req.url === '/api/request') {
console.log(magenta('---------------------------------------------'));
const { url, verb, body } = req.body;
let cookiesHeader = '';
if (Object.keys(req.cookies).length > 0) {
console.log(req.cookies);
cookiesHeader = Object.entries(req.cookies)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
console.log(magenta('PROXY_SERVER: cookies received in the request by proxy server:'));
console.log(cookiesHeader);
}
try {
const remoteServerResponse = await fetch(url, {
method: verb,
headers: {
'Content-Type': 'application/json',
Cookie: cookiesHeader,
},
body: verb !== 'GET' ? JSON.stringify(body) : undefined,
agent: url.startsWith('https:') ? agent : null, // Ignore SSL certificate errors
});
const responseText = await remoteServerResponse.text();
// Get the cookies from the response headers
const incomingCookies = remoteServerResponse.headers.raw()['set-cookie'];
// Set the cookies for the response
if (incomingCookies) {
console.log(incomingCookies);
incomingCookies.forEach((cookieString) => {
res.append('Set-Cookie', cookieString);
});
}
res.status(remoteServerResponse.status).send(responseText);
} catch (error) {
console.error(error);
res.status(500).send(error.message);
}
} else {
res.status(200).send({ objects: [
{
name: "vercel"
}
] });
}
});
});
});
};