2016-08-11 4 views
0

私の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 
} 
] 
+0

「commentJSON」には正確に何が含まれていますか? –

+0

可能ですか? http://stackoverflow.com/questions/10110805/jquery-post-json-object-to-a-server/10110924#10110924 –

+0

@KevinB JQueryプラグインなので、自分のデータを読み書きする必要があります。 http ://viima.github.io/jquery-comments/ –

答えて

-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 
         }); 
       }, 
+0

質問を編集して、ファイルに追加する部分だけに絞り込んでください。 – nnnnnn

関連する問題