-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathnode_example.js
More file actions
36 lines (32 loc) · 1.11 KB
/
node_example.js
File metadata and controls
36 lines (32 loc) · 1.11 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
var http = require('http')
var server = http.createServer(function (request, response) {
var url = request.url
var data = url.split('?')
if(data[0] === '/suma') {
var suma = 0
var input = data[1].split('&')
input.forEach(function(numero) {
var splitted = numero.split('=')[1]
if(isNumeric(splitted)) {
//Ok, it's a number
var number = Number(splitted)
suma += number
} else {
//It's not a number, so we show an error message and sends to the client
response.writeHead(400, {'Content-Type': 'application/json'})
response.end(JSON.stringify({result:'error, el input debe ser numerico'}))
}
})
//If everithing was OK, we send code 200 response, using json format
response.writeHead(200, {'Content-Type': 'application/json'})
response.end(JSON.stringify({result:suma}))
}
})
/**
** isNumeric returns true if input is a number. This can be done using the oppsite behaviour from isNaN function
**/
function isNumeric(num) {
//isNaN returns false if the input is a number, true otherwise
return !isNaN(num)
}
server.listen(8080)