-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_http.ts
More file actions
49 lines (42 loc) · 1.51 KB
/
node_http.ts
File metadata and controls
49 lines (42 loc) · 1.51 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
import http from 'http';
const host = 'localhost';
const port = 3000;
const MAX_BODY_SIZE = 100 * 1024 * 1024; // 100 MB
const server = http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/example') {
let body = '';
let bodySize = 0;
req.on('data', chunk => {
bodySize += chunk.length;
if (bodySize > MAX_BODY_SIZE) {
res.writeHead(413, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Payload too large' }));
req.destroy(); // stop receiving more data
return;
}
body += chunk;
});
req.on('end', () => {
try {
const data = body;
console.log(data);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ success: true }));
} catch (err) {
console.error('Error parsing JSON:', err);
res.writeHead(400, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Invalid JSON' }));
}
});
} else {
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(
JSON.stringify({
error: 'Not Found',
message: `Route ${req.method} ${req.url} not found`,
})
);
}
});
console.log(`Starting Web Server on ${host}:${port}...`);
server.listen(port, host);