Node.js,Ajax发送和接收Json

使用Ajax,我试图只发送Json数据到节点服务器,不涉及处理,只是在发送时发出警报,并在收到时发出警报:

这是我的html5:简单的button,带有onclick函数来触发函数使用ajax调用

<!DOCTYPE HTML> <html> <head> <script> function send() { //alert("Hello World"); $.ajax ({ type: "post", url: "http://localhost:8000", dataType: "json", contentType: "application/json; charset=UTF-8", data: JSON.stringify({name: "Dennis", address: {city: "Dub", country: "IE"}}) }).done(function ( data ) {alert("ajax callback response:" + data); }); </script> </head> <body> <button onclick="send()">Click Me!</button> </body> </html> 

这是我的节点服务器的一部分:用于创build服务器并侦听某些操作

 var port = 8000; var server = http.createServer(); server.on('request', request); server.listen(port); function request(request, response) { var store = ''; response.writeHead(200, {"Content-Type": "text/json"}); request.on('data', function(data) { store += data; }); request.on('end', function() { store = JSON.parse(store); console.log(store); response.end(store); }); } 

没有警报被解雇,所以我不认为阿贾克斯正在试图发送信息。

在服务器端试试这个:

 var port = 8000; var http = require("http"); var server = http.createServer(); server.on('request', request); server.listen(port); function request(request, response) { var store = ''; request.on('data', function(data) { store += data; }); request.on('end', function() { console.log(store); response.setHeader("Content-Type", "text/json"); response.setHeader("Access-Control-Allow-Origin", "*"); response.end(store) }); } 

这在客户端:

 $.ajax ({ type: "POST", url: "http://localhost:8000", crossDomain:true, dataType: "json", data:JSON.stringify({name: "Dennis", address: {city: "Dub", country: "IE"}}) }).done(function ( data ) { alert("ajax callback response:"+JSON.stringify(data)); }) 

希望这对你有用

你不能使用一个普通的JavaScript对象的response.write()response.end() ,你只能写缓冲区或string。

所以你需要做的是先把对象串起来。 要么改变response.end(store); to response.end(JSON.stringify(store)); 或者不要store = JSON.parse(store); (除非你正在validationJSON – 如果是这种情况,你应该把它包装在try-catch中,因为JSON.parse()会抛出parsing错误)。