Hi! I'm an absolute beginner trying to create a REST api with node.js, express, and a JSON file following a tutorial online. I'm able to implement all the verbs, but I'm stuck at this part where I want to GET multiple objects from my JSON file. I've tried looking for a way to implement this but I couldn't find any solutions because... I think I'm looking for the wrong thing. I hope someone will be able to help.I'm using this snippet to GET all the books from the year 2020.app.get('/books/:year', (req, res) => { fs.readFile(dataPath, 'utf8', (err, data) => { const bookYear = req.params['year']; const bookByYear = JSON.parse(data); const book = bookByYear.find(book => book.year === bookYear); res.status(200).send(book); }); }); However, it returns the first "year" : "2020" object only. How do I get all the objects satisfying the criteria, and not just the first one? Oh and here's my JSON file.[ { "title": "ABC", "author": "Author A", "year": "2020" }, { "title": "XYZ", "author": "Author B", "year": "2020" } ]I feel like I'm missing something small, but I'm too much of a noob to figure anything out... Any help will be appreciated, thank you so much.
Submitted June 12, 2020 at 04:37PM by kokindenjunotachi
No comments:
Post a Comment