简体   繁体   中英

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);

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

Cross domain ajax requires special support from your server.

Either CORS: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing Which not all browsers support yet. It involves special headers in both the request and response that tell the browser that one domain is allowed to communicate with the other, and for what data.

Or JSONP: http://en.wikipedia.org/wiki/JSONP WHich will work anywhere, but has some implementation limitations. It involves the server wrapping the response in a javascript function callback that will execute and pass in that data you want.

Either way, the server needs to be setup for each of these approaches.

I think your problem is Same Origin Policy . Your browser must get webpage from node.js instance.

Otherwise, you must use something like CORS . There also good question on SO: Ways to circumvent the same-origin policy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM