我的ajax to 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
以下是我的获取请求理解的内容:
[
{
"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
}
]
答案 0 :(得分:-1)
将我的ajax调用更改为此选项使我的get请求可读。但它覆盖了JSON文件中的数据。我希望它只是添加它。
postComment: function(commentJSON, success, error) {
$.ajax({
type: 'post',
url: 'http://localhost:8080',
data: JSON.stringify([commentJSON]),
success: function(comment) {
success(comment)
},
error: error
});
},