I've been trying to figure out how to insert data into an array through an express router endpoint. Let's say I have an array located inside the data/data.js
directory and my router code looks something like this:
const express = require('express');
const bodyParser = require('body-parser');
const productRouter = express.Router();
//! bring data
const { products } = require('../data/data');
productRouter.use(bodyParser.json());
productRouter
.route('/')
.post((req, res, next) => {
if (req.body !== null) {
//some logic
} else {
products.push(req.body);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(products);
}
} else {
//handle error
}
});
module.exports = productRouter;
After using the POST method in the route endpoint, it adds the new data and responds with an updated array. However, when I check my express file, it still shows the old array. Why is the new data not being retained?
I would greatly appreciate any help in resolving this issue.
Following suggestions from @Aditya and @Andre Nuechter, I made some updates to my code:
.post((req, res, next) => {
if (req.body !== null) {
if (products.some((product) => product.id === req.body.id)) {
err = new Error('Product with id:' + req.body.id + ' already exists');
err.status = 404;
return next(err);
} else {
const data_path = path.join(__dirname, '../data/data.js');
fs.appendFileSync(data_path, JSON.stringify(req.body));
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(products);
}
} else {
err = new Error('Body does not contain product information');
err.status = 404;
return next(err);
}
});
However, this results in adding the new data as shown below:
exports.products = [
{
title: 'camera',
imageUrl: 'https://source.unsplash.com/gGgoDJRD2WM/300x300',
id: 1,
},
...
]
exports.orders = [];
{"title":"mens","imageUrl":"https://source.unsplash.com/1-nx1QR5dTE/300x300","id":"6"}
This is not the desired output. Is there a way to add this to the products array or perhaps a better approach to achieve this?