Basically I can get the whole list from json file but I cannot figure out how to get concrete item. When I use postman, path: http://localhost:3000/book/2 for example it returns bookcode does not exist
app.get('/book/list', (req, res) => {
const books = getBookData()
res.send(books)
})
app.get("/book/:code", (req, res) => {
const code = req.params.code
const existsBook = getBookData();
const filterBook = existsBook.filter(book => book.code !== code)
if (existsBook.length === filterBook.length) {
return res.status(400).send({error: true, msg: 'bookcode does not exist'})
}
})
const getBookData = () => {
const jsonData = fs.readFileSync('books.json')
return JSON.parse(jsonData.toString())
}
here is json file
[{"code":2,"name":"Name of the wind","author":"Patrrick Rothfuss"},{"code":3,"name":"Wise Man's Fear","author":"Patrrick Rothfuss"},{"code":4,"name":"The Doors of Stone","author":"Patrrick Rothfuss"}]
This may be because req.query.code is by default a string, not number. This tripped me up once.
A reliable solution would be to use parseInt.
const code = parseInt(req.params.code)
Not working? You could also try a traditional Number ()
const code = Number(req.params.code)