1

I have a task to implement a pseudo cart page and when I click on checkout i want to send a request to a json file "ordersTest.json" with a following structure: { "orders": [] }. So when a post request is sent i have to put the data in that orders array in the json. I am completely new to Nodejs and express. This is my first project on it and i came up with a very simple server.

const express = require('express')
const path = require('path')
const fs = require('fs')
const url = require('url')
const bodyParser = require('body-parser')
const app = express()
const ordersJson = require('./public/ordersTest.json');


app.use(bodyParser.json());       
app.use(bodyParser.urlencoded({    
   extended: true
})); 
app.post('/api/orders', (req, res) => {
    let body = req.body;
    console.log(body);
    fs.appendFile('./public/ordersTest.json', JSON.stringify(body), err => {
        if (err) console.log(err);
    })
})

But this thing only appends it to the end of the file. I need to put it inside this orders array

This is my ajax passing an example object in the body of the post:

$(".btn-checkout").on('click', function() {
    let date = new Date();
    $.ajax({
        method : "POST",
        url: "/api/orders",
        data : {a: "abc"},//{ order: "order",date: date.toDateString(), order: JSON.stringify(cart)},
        success : function(success){
            console.log(success,'success');
        },
        error : function(err) {
            console.log(err);
        }
    });
    clearCart();
    displayClearedCart();
});

1 Answer 1

2

You need to parse the JSON file and then treat it like an object. Once you are done with it, convert it to JSON again and overwrite your file. like this

app.post('/api/orders', (req, res) => {
    let body = req.body;
    var ordersTest = require('./public/ordersTest.json');
    ordersTest.orders.push(body);
    fs.writeFile('./public/ordersTest.json', JSON.stringify(ordersTest), function(err) {
      if (err) res.sendStatus(500)
      res.sendStatus(200);
    });
})

Not tested, please fix typo error if any.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Worked perfectly

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.