Я написал код для передачи данных со страницы HTML (клиент) в server.js (node.js), и он будет сохранять файл JSON локально.
Это мой 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');
и вот мой HTML-код, откуда я отправляю данные:
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.');
},
});
});
Итак, вывод, который я получаю, выглядит так в файле JSON:
"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"
но я хочу этот формат:
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,
}]
ТАК, как я могу этого достичь.
Я пытался с jsonstringify (body, null, 4), но это не работает.