简体   繁体   中英

how to get formated JSON data from node.js server?

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.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM