我正在尝试从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开发工作。 请帮助我把这件事搞定
答案 0 :(得分:0)
教授艾尔曼说 只是替换&#34; GET&#34;用&#34; POST&#34;得到我需要的东西 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>