Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  129] [ 3]  / answers: 1 / hits: 110397  / 13 Years ago, mon, march 21, 2011, 12:00:00

This is similar to Stream data with Node.js, but I don't feel that question was answered sufficiently.



I'm trying to use a jQuery ajax call (get, load, getJSON) to transfer data between a page and a node.js server. I can hit the address from my browser and see 'Hello World!, but when I try this from my page, it fails and shows that I get no response back. I setup a simple test page and hello world example to test this:



<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=utf-8 />
<title>get test</title>
</head>
<body>
<h1>Get Test</h1>
<div id=test></div>

<script src=//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js></script>
<script>
$(document).ready(function() {
//alert($('h1').length);
$('#test').load('http://192.168.1.103:8124/');
//$.get('http://192.168.1.103:8124/', function(data) {
// alert(data);
//});
});
</script>
</body>
</html>


and



var http = require('http');

http.createServer(function (req, res) {
console.log('request received');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello Worldn');
}).listen(8124);

More From » jquery

 Answers
58

If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:



var http = require('http');

http.createServer(function (req, res) {
console.log('request received');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('_testcb('{message: Hello world!}')');
}).listen(8124);


and client side JavaScript/jQuery:



$(document).ready(function() {
$.ajax({
url: 'http://192.168.1.103:8124/',
dataType: jsonp,
jsonpCallback: _testcb,
cache: false,
timeout: 5000,
success: function(data) {
$(#test).append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + + errorThrown);
}
});
});


There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.


[#93170] Friday, March 18, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kevonmoisesf

Total Points: 693
Total Questions: 101
Total Answers: 128

Location: Reunion
Member since Mon, Dec 28, 2020
3 Years ago
kevonmoisesf questions
Sat, Jan 23, 21, 00:00, 3 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
Wed, Jun 12, 19, 00:00, 5 Years ago
;