簡體   English   中英

通過javascript將JSON數據從客戶端發送到服務器

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

我試圖從client.html發送一個簡單的字符串化JSON對象,由server.js使用http接收。 服務器是使用Node.js實現的。問題是它不會從客戶端發送到服務器(因為我期望它是一個應該工作的POST方法)。 客戶端從服務器接收響應並在控制台上顯示它。

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

// 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}`)
})

要運行server.js,請在命令終端中輸入:

node server.js

旁注:我知道這個問題很可能非常簡單,但我主要使用c ++,python,除了以后我從未在Web開發工作。 請幫助我把它搞定

根據教授阿爾曼的說法,用“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