R
R
rebyatyonok2017-05-23 16:03:03
JSON
rebyatyonok, 2017-05-23 16:03:03

How to write an object received via AJAX to an already existing JSON?

Good afternoon everyone! Question about interoperability between Node.js, Express and JSON.
The story is this: I have several forms whose values ​​I want to store in JSON. That is, I enter anything into the form, press the save button, and they fly to the server in the form of such an object:

{
  "name": "345678",
  "mail": "98765678233123123",
  "phone": "900213123",
  "date": "-----",
  "summ": "-----",
  "visits": "-----",
  "active": "-----"
}

I send the object to the server like this:
$('.modal__window__right__save div').click(function(){
            $.ajax({
                url: "http://localhost:3000",
                type: "POST",
                data: userStr,
                success: function() {
                    console.log('data was sent');
                },
                dataType: 'JSON'
            });

the server accepts this code with this one:
app.post('/', function (req, res, next) {
    req.addListener('data', function(postDataChunk) {

        // Может быть ошибка где то тут? 
        let postData = JSON.parse(postDataChunk);
        console.log('Новые данные получены');
        
        // Или где то тут? 
        jsonfile.writeFileSync('build/data/user.json', postData, {spaces: 2}, function(err){
            console.log(err);
        });
    });
    next();
});

and must write it to an already existing JSON array of the form:
{
  "users": [
       // here
   ]
}

The whole problem is that this code works, but each time it ends up overwriting the entire JSON.
That is, instead of a users object with many nested objects, it turns out one object that came from the client (the first code itself).
Where is my mistake - I can not understand. If you find her (or them) and explain what and how - I will be very grateful.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RidgeA, 2017-05-23
@rebyatyonok

because fs.writeFileSync opens the file in "w" mode by default

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question