-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (73 loc) · 2.22 KB
/
index.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// const http = require('http')
// const url = require('url')
const fs = require('fs')
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const { log } = require('console')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.get('/', (req, res) => {
res.status(200).send('<h1>Welcome to my Awesome books<h1>')
} )
app.get('/books', (req, res) => {
fs.readFile('books.json', (err, data) => {
if (err) {
console.log(err);
return
}
res.write(data)
res.end()
})
})
app.get('/new_book', (req, res) => {
let formHtml = `
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<form action="/new_book" method="POST">
<lable for="title">Book Title</lable>
<input type="text" name="title" placeholder="Enter book title"><br>
<lable for="author">Book Author</lable>
<input type="text" name="author" placeholder="Enter book author"><br>
<lable for="price">Book Price</lable>
<input type="text" name="price" placeholder="Enter book price"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
`
res.send(formHtml)
})
app.post('/new_book', (req, res) => {
fs.readFile('books.json', (err, data) => {
let books = JSON.parse(data)
let newBook = {
bookId: books.length + 1,
bookTitle: req.body.title,
bookAuthor: req.body.author,
bookPrice: req.body.price
}
books.push(newBook)
books = JSON.stringify(books, null, 4)
fs.writeFile('books.json', books, (err) => {
if (err) {
console.log(err);
}
console.log("Book added successfully");
})
})
res.redirect('/books')
})
app.get('/books/:id', (req, res) => {
fs.readFile('books.json', (err, data) => {
let books = JSON.parse(data)
let book = books[req.params.id - 1]
res.json(book)
})
})
app.listen(8080, () => {
console.log('App listen in port 8080');
})