一尘不染

Node.js,Ajax发送和接收Json

node.js

使用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正在尝试发送信息。


阅读 411

收藏
2020-07-07

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

希望这对你有用

2020-07-07