Node.js fetch data from node in jquery ajax callback

I have a jquery ajax call that sends a request to a node.js app that works great, the problem is I can't get the response with the jquery call.

JQuery

$(document).ready(function(){
    var listing = $('#listing');

    $.ajax
    ({
        url: "http://my.ip.is.here:3000/",
        cache: false,
        //timeout: 5000,
        success: function(data)
        {
            listing.append(data);
        }
    });

})

      

Node:

var s = http.createServer(function (req, res) {
    req.on('data', function(sock) {

      // SEND DATA BACK TO AJAX HERE

    });

});

s.listen(3000, 'my.ip.is.here');

console.log('Server running at http://my.ip.is.here:3000/');

      

How do I go about pulling data from a node.js app into my jquery callback? (and hopefully keeping the connection alive)

+3


source to share


1 answer


If you want to trigger a data event on the server, you need to send the data to the server, perhaps using a Jquery post method like:

var postSomething = function(){

    $.post
    (
        "http://127.0.0.1:3000/",
        {wooo:'wooo'},
        function(data)
        {
         console.log(data);
        }
    );
}

      

Also, when the server fires the data event, you have to write some data in the response object:

req.on('data', function(sock) {
      res.writeHead(200, {"Content-Type": "text/plain"});
      res.end("Hello!!");
});

      



However, if you just want to fetch data from the server, I don't think you need a data event on the server and can just handle the request like in:

var s = http.createServer(function (req, res) {
          res.writeHead(200, {"Content-Type": "text/plain"});
          res.end("Hello!!");
});

      

If you use "end" you abort the request, if you want to keep it active you can simply use "write". This way the connection is still active and you are passing data to the client every time you write data to the response object.

Hope this helps!

+3


source







All Articles