0

I wrote code to get the data from HTML page (client) to server.js (node.js) and it will save JSON file locally.

This is my server.js :

var http = require('http');
var util = require('util')
var fs = require('fs');
http.createServer(function (req, res) {
if (req.method == 'POST') {
console.log("POST");
var body = '';
req.on('data', function (data) {
    body += data;
    console.log("Partial body: " + body);

    fs.writeFile("./text1.json", JSON.stringify(body, null, 4),    (err) => {
        if (err) {
        console.error(err);
        return;
        }
        console.log("File has been created");
});
});
req.on('end', function () {
    console.log("Body: " + body);
});
res.writeHead(200, {'Content-Type': 'text/html','Access-Control-Allow-Origin': '*'});

res.end('callback(\'{\"msg\": \"OK\"}\')');
}
else
{
console.log("GET");
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('callback(\'{\"msg\": \"OK\"}\')');
}
}).listen(8090);
console.log('Server running on port 8090');

and Here my HTML code from where I am sending data :

data_frame = {
                "frame": i,
                "Objects_classname" : obj.getObjects()[1].text,
                "x_val":obj.left,
                "y_val":obj.top,
                "width":obj.width,
                "height" : obj.height
            }


            $.ajax({
                            url: 'http://127.0.0.1:8090',
                            // dataType: "jsonp",
                            data: data_frame,
                            type: 'POST',
                            jsonpCallback: 'callback', // this is not relevant to the POST anymore
                            success: function (data) {
                                var ret =  JSON.parse(JSON.stringify(data));
                                //$('#layer1').html(ret.msg);
                              //console.log(ret);
                                console.log('Success: ')
                            },
                            error: function (xhr, status, error) {
                                console.log('Error: ' + error.message);
                              //  $('#layer1').html('Error connecting to the server.');
                            },
                });
            });

So the output I am getting is like this in JSON file :

"output%5Bframe%5D=11&output%5BObjects_classname%5D=car2&output%5Bx_val%5D=518.94958&output%5By_val%5D=130.03093&output%5Bwidth%5D=65.58593999999994&output%5Bheight%5D=104.8877"height%5D=213.56171"

but I wants this format :

var data = [
{
"Frame_count":1,
output:[
    {
    "Objects_classname":"car1",
        "x_val":82.9883,
        "y_val":197.56245,
        "width":316.03088,
        "height":197.45451
    },

    {
    "Objects_classname":"car2",
        "x_val":522.4823,
        "y_val":170.47263,
        "width":64.66687,
        "height":61.78085
    },

    ],
    "Total_objects_detected":2,
},
{
"Frame_count":2,
output:[
    {
    "Objects_classname":"car1",
        "x_val":78.9991,
        "y_val":189.48058,
        "width":327.41028,
        "height":198.80226
    }

    ],
    "Total_objects_detected":1,
}]

SO how can i achieve this. I tried with jsonstringify(body, null, 4) but this is not working.

dishcode
  • 23
  • 1
  • 2
  • 9
  • Why you are not using `express` and `body-parser`? it would be really easy if you do it that way. – Dhaval Chaudhary Jan 07 '19 at 06:37
  • https://stackoverflow.com/questions/19696240/proper-way-to-return-json-using-node-or-express – Puneet Jan 07 '19 at 06:40
  • @DhavalChaudhary I don't know how to use it. Can you please elaborate more how to use it? – dishcode Jan 07 '19 at 06:41
  • hi dishcode, i ran your server and used [postman](https://www.getpostman.com) to send the raw data you have given. I just changed a small bit of code in the server file... i removed json.stringify and just wrote the raw data to the file. worked perfectly fine... – JustAMicrobe Jan 07 '19 at 06:49
  • by the way, you are using some variables in your example data_frame. please give a REAL data_frame that your are using. I dont see how one would get your expected result with this code as there is no loop anywhere to create the arrays. – JustAMicrobe Jan 07 '19 at 06:51
  • @JustAMicrobe I think you misunderstand with something. Expected result you are seeing (JSON) was written manually. – dishcode Jan 07 '19 at 08:32
  • @dishcode well you still can't get these arrays that you want to get by your code. You always write new data to the file, so this data has to have your expected JSON structure. To do this you need to loop through the frames and then through the objects and buil up your arrays. But your question concerns the url encoding that happens when you write your data to the file. I just removed this fs.writeFile("./text1.json", JSON.stringify(body, null, 4) with this fs.writeFile("./text1.json", body ... and it worked fine. – JustAMicrobe Jan 07 '19 at 10:48
  • now that i think about it, why do you first stringify and then parse your json again? just stringify should be enough. if you set the content-type to application/json in your ajax call, your server should be able to handle it anyway. – JustAMicrobe Jan 07 '19 at 10:55

1 Answers1

0

Try this as your server:

let express = require('express'),
fs = require('fs'),
bodyParser = require('body-parser'),
app = express(),
port = process.env.PORT || process.argv[2] || 8080;

app.use(bodyParser.json());

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname + '/index.html'));
});

app.post('/', function (req, res) {
   console.log(req.body);
   fs.writeFile("./text1.json", JSON.stringify(req.body, undefined, 4),    (err) => {
     if (err) {
      console.error(err);
      res.send(err);
     }
     console.log("File has been created");
     res.json(req.body);
   });
});

app.listen(port, function () {
   console.log('body-parser demo is up on port: ' + port);
});

This is you index.html file put it in same folder as your server.

<!DOCTYPE html>
<html>

<head>
   <title></title>
</head>
 <script src="https://code.jquery.com/jquery-3.3.1.min.js" 
 integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" 
 crossorigin="anonymous"></script>
 <script type="text/javascript">
    var data_frame = {
      "Objects_classname": "car1",
      "x_val": 82.9883,
      "y_val": 197.56245,
      "width": 316.03088,
      "height": 197.45451
    };
    $.ajax({
       url: '/',
       data: JSON.stringify(data_frame),
       type: 'POST',
       contentType: 'Application/json',
       success: function(data) {
            var ret = JSON.parse(JSON.stringify(data));
            console.log('Success: ')
       },
       error: function(xhr, status, error) {
          console.log('Error: ' + error.message);
       }
   });
  </script>
 <body>
 </body>
 </html>
Dhaval Chaudhary
  • 5,428
  • 2
  • 24
  • 39