如何与node.js一起使用jQuery ajax调用

这与使用Node.js的Stream数据类似,但我不觉得这个问题得到了充分的回答。

我试图使用jQuery ajax调用(get,load,getJSON)在页面和node.js服务器之间传输数据。 我可以从我的浏览器中打开地址,看到“Hello World!”,但是当我从我的页面尝试这个时,它失败了,并且显示我没有回应我设置了一个简单的testing页面和hello世界的例子来testing这个:

<!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> 

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

如果您的简单testing页面位于其他协议/域/端口上,而不是您的hello world node.js示例,那么您正在进行跨域请求并违反了相同的源策略,因此您的jQuery ajax调用(get和load)失败。 为了得到这个跨域的工作,你应该使用基于JSONP的格式。 例如node.js代码:

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

和客户端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); } }); }); 

还有其他方法可以实现这个function,例如通过设置反向代理或者使用express等框架完全构buildWeb应用程序。

感谢yojimbo的回答。 为了添加他的示例,我想使用jquery方法$ .getJSON,它在查询string中放置了一个随机callback,所以我也想在Node.js中parsing这个方法。 我也想传回一个对象并使用stringify函数。

这是我的客户端代码。

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

这是我的服务器端Node.js

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

我想你的HTML页面托pipe在不同的端口上。 在大多数浏览器中,相同的起始策略要求加载的文件与加载文件位于相同的端口上。

在服务器端使用类似下面的内容:

 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)