Search code examples
javascriptjquerynode.jsgetrequest

GET request in javascript to NodeJS


I'm trying to do a simple conection (request - response) from the javascript code on a web to a server in Node.js.

I have tried to make the request as follows:

var request = new XMLHttpRequest();
request.open('GET', 'http://localhost:4444/', false);
request.send(); 

if (request.status === 200) {
  console.log(request.responseText);
}

Running this code I got an error in FireBug

I have continued searching and I found that this method is only to make GET requests on the same domain. To make cross domain requests we must use other strategies.

I found a jQuery method, and it seems that i'm on the right way:

$.get(
    'http://localhost:4444/',
    function(data) {
        alert("sucess"); 
        //Do anything with "data"
    }
);

In this case I get the same response without the error.

It seems it works but the "alert" message is never shown! What happens? What am I doing wrong?

The Node.js server code is:

var http = require("http");

http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write("Response");
    response.end();
}).listen(4444);

Solution

  • So you're running into cross domain issues. You have a few options:

    1) since you're using node, use socket.io . It's cross domain compliant.

    On the client:

    <script src="Full path to were socket IO is held on your server//socket.io.js"></script>
    <script>
        var socket = io.connect();
    
        socket.on('some_callback', function(data){
            // receive data
        });
    
        socket.emit('some_other_callback', {'data': value}); //send data
    </script>
    

    Server:

    var io = require('socket.io').listen(server);
    
    // define interactions with client
    io.sockets.on('connection', function(socket){
        //send data to client
        socket.emit('some_callback', {'data': value});
    
        //recieve client data
        socket.on('some_other_callback', function(data){
            //do something
        }); 
    });
    

    2) Since you just want to use GET you can use JSONP

    $.getJSON('url_to_your_domain.com/?callback=?&other_data=something,
        function(data){
            //do something
        }
    );
    

    Here we pass your normal GET params as well as callback=?. You will return the following from your server:

    require('url');
    var r = url.parse(req.url,true);
    r.query.callback + '(' + some JSON + ')'
    

    3) If you don't care about all browser compatibility you can use CORS: You can see a much better example than I would be able to write Here