-
Notifications
You must be signed in to change notification settings - Fork 205
/
Copy pathapp.js
47 lines (34 loc) · 1.18 KB
/
app.js
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
const http = require('http');
const mathM = require('./math')
require('dotenv').config()
const PORT = process.env.PORT || 3000;
const handleRequest = (req, res) => {
const {url, method } = req;
const body = [];
let result
if (url === '/calculate' && method === 'POST') {
req.on('data', (chunk) => {
body.push(chunk);
});
req.on('end', () => {
const parsedBody = Buffer.concat(body).toString()
const bodyObject = JSON.parse(parsedBody);
const { action, num1, num2 } = bodyObject
if (action === 'sum') {
result = mathM.add(num1, num2)
} else if (action === 'subtract') {
result = mathM.subtract(num1, num2)
} else if (action === 'divide') {
result = mathM.divide(num1, num2)
} else if (action === 'multiply') {
result = mathM.multiply(num1, num2)
}
res.end(JSON.stringify({ result }))
})
}
}
const server = http.createServer(handleRequest);
server.listen(PORT, () => {
console.log(`Server is listening on port: ${PORT}`)
})
module.exports = server;