How to use jQuery ajax calls using node.js

This is similar to Data Stream with Node.js , but I donโ€™t feel that this question has been answered.

I am trying to use 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 to do this from my page, it fails and shows that I am not receiving a response. I am setting up a simple test page and a welcome 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 World\n'); }).listen(8124); 
+68
javascript jquery html ajax
Mar 21 2018-11-11T00:
source share
4 answers

If your simple test page is on a different protocol / domain / port than in your node.js hello world, you are making cross-domain requests and violating the same origin policy so your jQuery ajax (get and load) calls fail. To get this working cross-domain, you must use the JSONP 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 the client side of 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 other ways to do this, for example, by setting up a reverse proxy server or completely creating your web application using a framework such as express .

+83
Mar 21 2018-11-11T00:
source share

Thanks yojimbo for his answer. To add to its sample, I wanted to use the jquery $ .getJSON method, which places a random callback in the query string, so I also wanted to parse this into Node.js. I also wanted to pass the object back and use the stringify function.

This is the code of my client side.

 $.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?", function(data){ alert(data); }, function(jqXHR, textStatus, errorThrown) { alert('error ' + textStatus + " " + errorThrown); }); 

This is my Node.js server side

 var http = require('http'); var querystring = require('querystring'); var url = require('url'); http.createServer(function (req, res) { //grab the callback from the query string var pquery = querystring.parse(url.parse(req.url).query); var callback = (pquery.callback ? pquery.callback : ''); //we probably want to send an object back in response to the request var returnObject = {message: "Hello World!"}; var returnObjectString = JSON.stringify(returnObject); //push back the response including the callback shenanigans res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(callback + '(\'' + returnObjectString + '\')'); }).listen(8124); 
+7
Mar 30 '11 at 12:28
source share

Suppose your html page is hosted on a different port. The same origin policy requires in most browsers that the downloaded file is on the same port as the download file.

+3
Mar 21 2018-11-11T00:
source share

On the server side, use something like the following:

 http.createServer(function (request, response) { if (request.headers['x-requested-with'] == 'XMLHttpRequest') { // handle async request var u = url.parse(request.url, true); //not needed response.writeHead(200, {'content-type':'text/json'}) response.end(JSON.stringify(some_array.slice(1, 10))) //send elements 1 to 10 } else { // handle sync request (by server index.html) if (request.url == '/') { response.writeHead(200, {'content-type': 'text/html'}) util.pump(fs.createReadStream('index.html'), response) } else { // 404 error } } }).listen(31337) 
+1
Apr 26 '11 at 19:09
source share



All Articles