私のajaxでnode.jsのJSONファイルへのポストに問題があります。それは正常に動作しますが、正しくフォーマットされていないと私は推測しています。なぜなら、データを読み込むと、読めないと思っているので、それが戻ってこないからです。ここでNode.JSのJSONファイルへの投稿が正しくフォーマットされていない
はAJAX呼び出しです:ここでは
postComment: function(commentJSON, success, error) {
$.ajax({
type: 'post',
url: 'http://localhost:8080',
data: commentJSON,
success: function(comment) {
success(comment)
},
error: error
});
},
はを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/');
は、そのファイルに書き込む方法です:
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
ここに私のget要求のアンダー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
}
]
「commentJSON」には正確に何が含まれていますか? –
可能ですか? http://stackoverflow.com/questions/10110805/jquery-post-json-object-to-a-server/10110924#10110924 –
@KevinB JQueryプラグインなので、自分のデータを読み書きする必要があります。 http ://viima.github.io/jquery-comments/ –