通过javascript发送JSON数据从客户端到服务器通过javascript
问题描述:
我想从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开发中工作。 请帮我弄成
答
这个根据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>
可以使用express.js框架。 –
请问request.on('data'...'从来没有触发因为你没有POST或者发送表单吗? – James
send(argument)“[如果请求方法是GET或者HEAD,那么参数会被忽略和请求正文设置为空](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send)“ –