2017-05-05 204 views
1

我想從client.html發送一個簡單的字符串化的JSON對象由server.js使用http接收。 服務器使用Node.js實現 問題是它只是不會從客戶端發送到服務器(因爲我期待它是一個應該工作的POST方法)。客戶端收到服務器的響應並將其顯示在控制檯上。通過javascript發送JSON數據從客戶端到服務器通過javascript

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,而且我有neve除了以後,r在web開發中工作。 請幫我弄成

+0

可以使用express.js框架。 –

+0

請問request.on('data'...'從來沒有觸發因爲你沒有POST或者發送表單嗎? – James

+1

send(argument)「[如果請求方法是GET或者HEAD,那麼參數會被忽略和請求正文設置爲空](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send)「 –

回答

0

這個根據ProfessorAllman 只是更換 「GET」 和 「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("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> 
相關問題