app.get('/api/notes/:id', (req, res, next) => {
fs.readFile(dataPath, 'utf-8', (err, data) => {
if (err) {
throw err;
}
const wholeData = JSON.parse(data);
const objects = wholeData.notes;
const inputId = parseInt(req.params.id);
if (inputId <= 0) {
res.status(400).json({error: 'id must be a positive integer'});
} else {
let found = false;
for (const key in objects) {
if (parseInt(objects[key].id) === inputId) {
found = true;
res.status(200).json(objects[key]);
break;
}
}
if (!found) {
res.status(404).json({error: `Oops! There is no id ${inputId}`});
}
}
})
})
This is the code I have implemented so far. I have set this globally:
const dataPath = 'data.json';
Here is what the content of the data.json file looks like:
{
"nextId": 5,
"notes": {
"1": {
"id": 1,
"content": "The event loop is how a JavaScript runtime pushes asynchronous callbacks onto the stack once the stack is cleared."
},
"2": {
"id": 2,
"content": "Prototypal inheritance is how JavaScript objects delegate behavior."
},
"3": {
"id": 3,
"content": "In JavaScript, the value of 'this' is determined when a function is called; not when it is defined."
},
"4": {
"id": 4,
"content": "A closure is formed when a function retains access to variables in its lexical scope."
}
}
}
When I run the command http -v get :3000/api/notes/3 in the terminal, the error message gets triggered instead of returning the object with id 3.
However, if I remove the error message if statement, the code successfully retrieves the object from the JSON file. How can I solve this issue?