Ich habe Probleme mit meinem Ajax zu node.js Post in JSON-Datei. Es funktioniert richtig, aber es ist nicht richtig formatiert, nehme ich an. Denn wenn es die Daten liest, kommt es nicht zurück aufgrund dessen, was ich vermute, dass es denkt, dass es nicht lesbar ist. HierNode.JS Post in JSON-Datei nicht korrekt formatiert
ist die AJAX Aufruf:
postComment: function(commentJSON, success, error) {
$.ajax({
type: 'post',
url: 'http://localhost:8080',
data: commentJSON,
success: function(comment) {
success(comment)
},
error: error
});
},
Hier ist die node.js:
var http = require('http');
var fs = require('fs');
http.createServer(function(req, res) {
console.log('Request received: ');
if (req.method == 'POST') {
req.on('data', function(chunk) {
console.log(data);
fs.writeFile("comments-data.json", chunk, function(err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
})
});
res.end('{"msg": "success"}');
};
if (req.method == 'GET') {
fs.readFile("comments-data.json", 'utf8', function(err, data) {
if (err) {
return console.log(err);
} else {
res.setHeader("Content-Type", "text/json");
res.setHeader("Access-Control-Allow-Origin", "*");
res.end(data)
}
})
};
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');
Hier ist, wie es schreibt in die Datei:
id=c1&parent=&created=2016-08-11T19%3A24%3A31.418Z&modified=2016-08-11T19%3A24%3A31.418Z&content=test&fullname=&profile_picture_url=https%3A%2F%2Fviima-app.s3.amazonaws.com%2Fmedia%2Fuser_profiles%2Fuser-icon.png&created_by_current_user=true&upvote_count=0&user_has_upvoted=false
Hier ist was meine Anfrage unterfragt tands:
[
{
"id": 1,
"parent": null,
"created": "2015-01-01",
"modified": "2015-01-01",
"content": "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed posuere interdum sem. Quisque ligula eros ullamcorper quis, lacinia quis facilisis sed sapien. Mauris varius diam vitae arcu.",
"fullname": "Simon Powell",
"profile_picture_url": "https://app.viima.com/static/media/user_profiles/user-icon.png",
"created_by_admin": false,
"created_by_current_user": false,
"upvote_count": 3,
"user_has_upvoted": false
}
]
Was genau enthält 'commentJSON'? –
möglich dupe? http://stackoverflow.com/questions/10110805/jquery-post-json-object-to-a-server/10110924#10110924 –
@KevinB Es ist ein JQuery-Plugin, so dass es lesen und schreiben sollte es eigene Daten würde ich annehmen, http : //viima.github.io/jquery-comments/ –