error: send data from html page to server and receive some data from server

error: send data from html page to server and receive some data from server

当我 运行 此代码时,我无法发送和接收数据。我请求更正我的代码 这是服务器端代码

var http = require("http") ;
var fs = require("fs") ;
http.createServer(function(req,res){
  if(req.url == '/'){
    fs.readFile('post.html',function(err,data){
      res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
      res.write(data);
      res.end();
    });
  }
  else if (req.url == '/dat') {
    req.on('data', function (data){
      console.log(data.toString());
      console.log("yo");

    });
    console.log("second");
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.write("Hi, Server is still alive and awaiting your orders Dear User :)");
    res.end() ;
  }
  else{
    console.log("third");
  }
}).listen(2000);

这是客户端代码

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.post("http://localhost:2000/dat"),
        JSON.stringify({
          name: "Donald Duck",
          city: "Duckburg"
        }),
        function(data,status){
            alert("Data: " + data + "\nStatus: " + status);
        }

    });
});
</script>
</head>
<body>

<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>

我将这两个代码保存在同一个文件夹中并尝试编译。我成功地 运行 这段代码,但在对代码做了一些小改动之后。代码停止工作 我无法撤消它。如果可能的话,我需要更正我的代码。

你jQuery代码应该这样写

$("button").click(function() {
  $.post(
    "http://localhost:2000/dat",
    JSON.stringify({
      name: "Donald Duck",
      city: "Duckburg"
    }),
    function(data, status) {
      alert("Data: " + data + "\nStatus: " + status);
    }
  );
});