Repository navigation
Expand file tree
/
Copy pathcors-proxy.js
More file actions
86 lines (75 loc) · 2.3 KB
/
Copy pathcors-proxy.js
File metadata and controls
86 lines (75 loc) · 2.3 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { createServer } from 'node:http';
import { request } from 'node:https';
const PORT = 3001;
const server = createServer((req, res) => {
// Handle CORS preflight
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE, OPTIONS'
);
res.setHeader(
'Access-Control-Allow-Headers',
'Content-Type, Authorization, X-Request-ID, X-Retry-Count'
);
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// Get the target URL from query parameter
const urlParts = req.url?.split('?url=');
if (!urlParts || urlParts.length < 2) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Missing target URL parameter' }));
return;
}
// Decode the URL parameter
const targetUrl = decodeURIComponent(urlParts[1]);
if (!targetUrl) {
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Empty target URL' }));
return;
}
// Parse the target URL
let url;
try {
url = new URL(targetUrl);
} catch (error) {
console.error('Invalid URL:', targetUrl, error);
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid target URL', url: targetUrl }));
return;
}
console.log(`Proxying request to: ${url.href}`);
// Forward the request
const proxyReq = request(
{
hostname: url.hostname,
port: url.port || (url.protocol === 'https:' ? 443 : 80),
path: url.pathname + url.search,
method: req.method,
headers: {
...req.headers,
host: url.hostname,
},
},
(proxyRes) => {
res.writeHead(proxyRes.statusCode || 200, proxyRes.headers);
proxyRes.pipe(res);
}
);
proxyReq.on('error', (err) => {
console.error('Proxy error:', err);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Proxy error', details: err.message }));
});
// Forward the request body
req.pipe(proxyReq);
});
server.listen(PORT, () => {
console.log(`CORS proxy running on http://localhost:${PORT}`);
console.log(
`Usage: http://localhost:${PORT}?url=${encodeURIComponent('https://api.openai.com/v1/chat/completions')}`
);
});