Node.js, Ajax sending and receiving Json

后端 未结 2 1832
心在旅途
心在旅途 2020-12-14 13:37

Using Ajax, I\'m trying to just send Json data to a node server no processing involved just alerting when it\'s sent and alerting when it\'s received:

This is my ht

相关标签:
2条回答
  • 2020-12-14 14:17

    try this on the server side:

    var port = 8000;
    var http = require("http");
    var server = http.createServer();
    server.on('request', request);
    server.listen(port);
    function request(request, response) {
        var store = '';
    
        request.on('data', function(data) 
        {
            store += data;
        });
        request.on('end', function() 
        {  console.log(store);
            response.setHeader("Content-Type", "text/json");
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.end(store)
        });
     }  
    

    and this on the client side:

    $.ajax
    ({
      type: "POST",
      url: "http://localhost:8000",
      crossDomain:true, 
      dataType: "json",
      data:JSON.stringify({name: "Dennis", address: {city: "Dub", country: "IE"}})
     }).done(function ( data ) {
          alert("ajax callback response:"+JSON.stringify(data));
       })
    

    Hope this works for you

    0 讨论(0)
  • 2020-12-14 14:22

    You can't use response.write() or response.end() with a plain javascript object, you can only write Buffers or strings.

    So what you need to do is stringify the object first. Either change the response.end(store); to response.end(JSON.stringify(store)); or don't store = JSON.parse(store); in the first place (unless you are doing it to validate the JSON -- and if that was that case you should wrap it in a try-catch because JSON.parse() will throw on parse error).

    0 讨论(0)
提交回复
热议问题