-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (59 loc) · 1.94 KB
/
Copy pathserver.js
File metadata and controls
66 lines (59 loc) · 1.94 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
const http = require("http");
const https = require("https");
const fs = require("fs");
const path = require("path");
const HOST = "127.0.0.1";
const PORT = 3000;
const BINANCE_BASE_URL = "https://eapi.binance.com";
http
.createServer((req, res) => {
console.log(`Serving file: ${req.url}`);
// Proxy API requests to Binance (CORS)
if (req.url.startsWith("/api/binance/")) {
if (req.method === "OPTIONS") {
res.writeHead(204, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Accept",
});
return res.end();
}
const upstreamPath = req.url.replace("/api/binance", "");
const upstreamUrl = new URL(upstreamPath, BINANCE_BASE_URL);
https
.get(upstreamUrl, (apiResponse) => {
res.writeHead(apiResponse.statusCode || 500, {
"Content-Type":
apiResponse.headers["content-type"] || "application/json",
"Access-Control-Allow-Origin": "*",
});
apiResponse.pipe(res);
})
.on("error", (err) => {
res.writeHead(500);
res.end(`Proxy error: ${err.message}`);
});
return;
}
let file = req.url === "/" ? "index.html" : req.url;
const filePath = path.join(__dirname, file);
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
return res.end("Not found");
}
// Content type specification
const extension = path.extname(filePath);
let contentType = "text/html";
if (extension === ".js") {
contentType = "text/javascript";
} else if (extension === ".css") {
contentType = "text/css";
}
res.writeHead(200, { "Content-Type": contentType });
res.end(data);
});
})
.listen(PORT, HOST, () => {
console.log(`Server running at http://${HOST}:${PORT}`);
});