-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocal-proxy.js
More file actions
117 lines (99 loc) · 3.62 KB
/
local-proxy.js
File metadata and controls
117 lines (99 loc) · 3.62 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const http = require('http');
const https = require('https');
const url = require('url');
// Отключаем проверку SSL сертификатов для обхода проблем с TLS
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
// Конфигурация
const LOCAL_PORT = 3001;
const WORKER_URL = 'https://varim-ml-rag-proxy.crazyfrogspb-rag.workers.dev';
// Создаем HTTP сервер
const server = http.createServer((req, res) => {
// Настройка CORS
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
// Обработка preflight запросов
if (req.method === 'OPTIONS') {
res.writeHead(200);
res.end();
return;
}
// Только POST запросы
if (req.method !== 'POST') {
res.writeHead(405, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Method not allowed' }));
return;
}
// Собираем тело запроса
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
// Парсим URL для определения эндпоинта
const parsedUrl = url.parse(req.url);
const targetUrl = WORKER_URL + parsedUrl.pathname;
console.log(`Проксируем запрос: ${req.method} ${targetUrl}`);
console.log('Тело запроса:', body);
// Создаем запрос к Cloudflare Worker
const options = {
method: req.method,
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
'Origin': 'http://localhost:4002',
'User-Agent': 'Local-Proxy/1.0'
}
};
const workerReq = https.request(targetUrl, options, (workerRes) => {
console.log(`Ответ от worker: ${workerRes.statusCode}`);
// Копируем заголовки ответа
Object.keys(workerRes.headers).forEach(key => {
if (key.toLowerCase() !== 'access-control-allow-origin') {
res.setHeader(key, workerRes.headers[key]);
}
});
res.writeHead(workerRes.statusCode, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
});
// Передаем данные ответа
workerRes.on('data', chunk => {
res.write(chunk);
});
workerRes.on('end', () => {
res.end();
});
});
workerReq.on('error', (error) => {
console.error('Ошибка запроса к worker:', error);
res.writeHead(500, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
error: 'Proxy error',
message: 'Не удалось связаться с Cloudflare Worker'
}));
});
// Отправляем тело запроса
if (body) {
workerReq.write(body);
}
workerReq.end();
});
});
server.listen(LOCAL_PORT, () => {
console.log(`🚀 Локальный прокси запущен на http://localhost:${LOCAL_PORT}`);
console.log(`📡 Проксирует запросы к ${WORKER_URL}`);
console.log('');
console.log('Использование:');
console.log(`POST http://localhost:${LOCAL_PORT}/chat`);
console.log('');
});
// Обработка завершения
process.on('SIGINT', () => {
console.log('\n👋 Останавливаем прокси...');
server.close(() => {
console.log('✅ Прокси остановлен');
process.exit(0);
});
});