Thursday, September 22, 2022

Route handler for POST request to add JSON item

Route handler for POST request to add JSON item => solution without database

app.post('/api/v1/cards', (req, res) => {
// console.log(req.body);
// solution to work without database
const newId = cards[cards.length - 1].id + 1;
const newCard = Object.assign({ id: newId }, req.body);

cards.push(newCard);

fs.writeFile(
`${__dirname}/data/card-data.json`,
JSON.stringify(cards),
(err) => {
res.status(201).json({
status: 'success',
data: { images: newCard },
});
}
); // use asynchronous writeFile
});

node

No comments:

Post a Comment