-
Notifications
You must be signed in to change notification settings - Fork 0
/
api-practice.js
52 lines (46 loc) · 1.33 KB
/
api-practice.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
48
49
50
51
52
const http = require("http");
const url = require("url");
const port = 3000;
const hostname = 'localhost'
const server = http.createServer((req, res) => {
const reqUrl = url.parse(req.url, true);
if (reqUrl.pathname === '/sample1' && req.method === 'GET') {
console.log("GOT A GET");
sampleRequest(req, res);
} else if (reqUrl.pathname === '/sample1' && req.method === 'POST') {
console.log('Got a post');
testRequest(req, res);
}
});
server.listen(port, hostname, () => {
console.log("server running");
})
testRequest = (req, res) => {
let body = '';
req.on('data', (chunk) => {
body += chunk;
});
req.on('end', () => {
const post_body = JSON.parse(body);
let response = {
name: post_body.name,
age: post_body.age,
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response.name + " " + response.age));
});
}
sampleRequest = (req, res) => {
let reqUrl = url.parse(req.url, true);
let name = 'World';
if (reqUrl.query.name) {
name = reqUrl.query.name;
}
let response = {
name: name
}
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response.name));
}