Node.js, Ajax 发送和接收 Json

Posted

技术标签:

【中文标题】Node.js, Ajax 发送和接收 Json【英文标题】:Node.js, Ajax sending and receiving Json 【发布时间】:2014-07-10 04:18:59 【问题描述】:

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

这是我的html5:带有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>

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

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

没有警报被触发,所以我认为 ajax 没有尝试发送信息。

【问题讨论】:

打开你的控制台,你有没有看到任何错误? 打开你的开发者工具Net标签,你看到你期望的请求和期望的响应了吗? 当你有一个 text/plain 内容类型时,你为什么要告诉 jQuery 期待 JSON?为什么要发送没有响应正文的 200 响应? @Quentin 好的,我明白我做错了!现在它声明我的发送未被引用 将您的 JS 粘贴到 jshint.com 中(但我希望在加载文档时该错误会显示在 JS 控制台中)。 【参考方案1】:

在服务器端试试这个:

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

希望这对你有用

【讨论】:

这个例子成功了,谢谢!在“IE” 之后缺少一个括号只是一件事,它应该是“IE”)【参考方案2】:

您不能将response.write()response.end() 与纯javascript 对象一起使用,您只能编写缓冲区或字符串。

所以你需要做的是首先对对象进行字符串化。要么将response.end(store); 更改为response.end(JSON.stringify(store));,要么首先不要store = JSON.parse(store);(除非您这样做是为了验证JSON——如果是这种情况,您应该将它包装在一个try-catch 中,因为@ 987654326@ 会抛出解析错误)。

【讨论】:

以上是关于Node.js, Ajax 发送和接收 Json的主要内容,如果未能解决你的问题,请参考以下文章