-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
59 lines (46 loc) · 1.84 KB
/
Copy pathserver.js
File metadata and controls
59 lines (46 loc) · 1.84 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
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 5000;
http.createServer((req, res) => {
if (req.method === 'GET') {
const filePath = path.join(__dirname, 'calculator.html');
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(500);
res.end('Server Error');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
}
else if (req.method === 'POST' && req.url === '/calculate') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
try {
let { expression } = JSON.parse(body);
// Replace safe symbols
expression = expression.replace(/÷/g, '/')
.replace(/×/g, '*')
.replace(/−/g, '-');
// Only allow numbers, operators, and decimals
if (!/^[0-9+\-*/.() ]+$/.test(expression)) {
throw new Error("Invalid characters");
}
// Evaluate expression safely
const result = Function(`return ${expression}`)(); // safe for simple expressions
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ result }));
} catch (err) {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ result: 'Error' }));
}
});
}
}).listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});