-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.mjs
70 lines (57 loc) · 1.79 KB
/
server.mjs
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
import express from "express";
import fetch from "node-fetch";
import cors from "cors";
import helmet from "helmet";
import path from "path";
import { fileURLToPath } from "url";
import rateLimit from "express-rate-limit";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
app.disable("x-powered-by");
// Enable CORS with specific options
let corsOptions = {
origin: "*", // Sensitive
};
app.use(cors(corsOptions));
app.use(
helmet({
contentSecurityPolicy: false,
}),
);
app.use(express.json()); // to parse JSON bodies
// Implement rate-limiting for the /leetcode route
const leetcodeLimiter = rateLimit({
windowMs: 5 * 60 * 1000, // 15 minutes
max: 1000, // limit each IP to 100 requests per windowMs
});
app.post("/leetcode", leetcodeLimiter, async (req, res) => {
// Input validation (to be implemented based on your requirements)
try {
const response = await fetch("https://leetcode.com/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify(req.body), // forward the body from the client request
});
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
const data = await response.json();
res.send(data);
} catch (error) {
console.error(error);
res.status(500).send("An error occurred");
}
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
// Serve static files from the React application
app.use(express.static(path.join(__dirname, "client", "build")));
// Handle React routing, return all requests to React app
app.get("*", (_, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});