I was just wondering how to add(push) data into an array via an express router endpoint. Suppose I have an array inside data/data.js
directory and my router code look 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;
When I involve POST method in the endpoint of my route then it push the new data and response with an updated array. But when I check my express file then it still the old array. Why I lost the data?
I heartily thank if anyone helps me to figure out this.
As @Aditya toke and @Andre Nuechter suggested I update my code like this:
.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 exit');
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 didnot contain product information');
err.status = 404;
return next(err);
}
});
But it pushes the new data like this:
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"}
Which is not what I want. Is there any way to add this to the products array? Or any better approach?