-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.js
More file actions
36 lines (30 loc) · 999 Bytes
/
Copy pathhttp.js
File metadata and controls
36 lines (30 loc) · 999 Bytes
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
const host = 'localhost'
const port = 8000
const books = JSON.stringify([
{ title: 'The Alchemist', author: 'Paulo Coelho', year: 1988 },
{ title: 'The Prophet', author: 'Kahlil Gibran', year: 1923 }
])
const authors = JSON.stringify([
{ name: 'Paulo Coelho', countryOfBirth: 'Brazil', yearOfBirth: 1947 },
{ name: 'Kahlil Gibran', countryOfBirth: 'Lebanon', yearOfBirth: 1883 }
])
const requestListener = function (req, res) {
res.setHeader("Content-Type", "application/json")
switch (req.url) {
case "/books":
res.writeHead(200);
res.end(books);
break
case "/authors":
res.writeHead(200);
res.end(authors);
break
default:
res.writeHead(404);
res.end(JSON.stringify({error:"Resource not found"}));
}
}
const server = http.createServer(requestListener)
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`)
})