简体   繁体   English

通过javascript将JSON数据从客户端发送到服务器

[英]Send JSON data from client to server via javascript

I am trying to send a simple stringified JSON object from client.html to be received by server.js using http. 我试图从client.html发送一个简单的字符串化JSON对象,由server.js使用http接收。 The server is implemented using Node.js The issue is that it just doesn't send from the client to the server (as I am expecting it's a POST method that should work). 服务器是使用Node.js实现的。问题是它不会从客户端发送到服务器(因为我期望它是一个应该工作的POST方法)。 While client receives the response from the server and shows it on the console. 客户端从服务器接收响应并在控制台上显示它。

Client.html Client.html

<!DOCTYPE html>
<head>
 <meta charset="utf-8"/>
 <title>Client </title>
</head>
<body>
<script>
function httpGetAsync(theUrl, callback)
{
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      callback(xmlHttp.responseText);
    }
   xmlHttp.open("GET", theUrl, true); // true for asynchronous
   xmlHttp.send(JSON.stringify({x: 5}));
}


httpGetAsync("http://127.0.0.1:3000", function(response) {
  console.log("recieved ... ", response);
});
</script>
</body>

server.js server.js

// content of index.js
const http = require('http')
const port = 3000

const requestHandler = (request, response) => {
  console.log(request.url)
  response.end('Hello Node.js Server!') // this is read on the client side
  request.on('data', function(data) {
    console.log("recieved: " + JSON.parse(data).x) // Not showing on the console !!!!
  })
}

const server = http.createServer(requestHandler)

server.listen(port, (err) => {
  if (err) {
    return console.log('something bad happened', err)
  }

  console.log(`server is listening on ${port}`)
})

to run server.js, type in the command terminal: 要运行server.js,请在命令终端中输入:

node server.js

Side Note: I know this question is most probably very trivial, but I have mostly worked with c++, python and I have never worked in web development stuff except later. 旁注:我知道这个问题很可能非常简单,但我主要使用c ++,python,除了以后我从未在Web开发工作。 Please help me get this into something 请帮助我把它搞定

According to ProfessorAllman just replacing "GET" with "POST" gets what I needed client.html 根据教授阿尔曼的说法,用“POST”取代“GET”得到了我需要的client.html

<!DOCTYPE html>
<head>
 <meta charset="utf-8"/>
 <title>Client </title>
</head>
<body>
<script>
function httpGetAsync(theUrl, callback)
{
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      callback(xmlHttp.responseText);
    }
   xmlHttp.open("POST", theUrl, true); // true for asynchronous
   xmlHttp.send(JSON.stringify({x: 5}));
}


httpGetAsync("http://127.0.0.1:3000", function(response) {
  console.log("recieved ... ", response);
});
</script>
</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM