Skip to content Skip to sidebar Skip to footer

Write Json Data From Front-end To Back-end In Nodejs

I have ButtonClick.js and TakeData.js files. I defined my json data in TakeData.js as below var dataObj = {}; var locationsObj = 'locations'; dataObj[locationsObj] = {}; dataOb

Solution 1:

Your backend needs to have an HTTP server listening on some port that is accessible to your frontend. Then your frontend needs to make an AJAX request to your backend (most likely a POST request) and send the required data in the request body.

Now, your backend needs to handle the request, get the data and write it to the file or do whatever you want with that.

Things to keep in mind:

  • use body-parser if you're using Express
  • remember about CORS

It's easier if you use a higher level framework on the backend like Express, Hapi, Restify, LoopBack etc. instead of the low level http module in Node.

It's also easier if you use a framework on the frontend like jQuery, Angular, React, Aurelia, Ember etc.

Solution 2:

The first step is to set up a RESTful POST operation (an HTTP POST) on your server. This is the typical service mechanism for what is sometimes called an AJAX call. Once you have the server set up to receive a string via the POST, you can serialize your objects on the client side and deserialize (reconstitute) the objects on the server side.

To serialize, you can use stringify on the client side. A simple web search for "stringify" will show you different ways to use stringify in a browser-independent, backward compatible way.

stringify(obj)

On the server side, node.js has a global JSON object. Use parse to reconstitute an object or objects from the string. Other major languages now have similar parser methods.

JSON.parse(strJSON)

To get started, you can test the mechanism with just one simple object. Then you can aggregate the objects in a JSON array or associative array and send them all at once in a single POST.


[1] There are frameworks that encapsulate this process, but it may be of value to you to NOT initially use them so you get a clear picture of the mechanics of a RESTful POST over the HTTP protocol. It is the key thing that a browser does when you submit an HTML form, and RESTful operations are key communications elements in today's IT world.

Post a Comment for "Write Json Data From Front-end To Back-end In Nodejs"