I am trying to send a simple stringified JSON object from client.html to be received by server.js using 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). While client receives the response from the server and shows it on the console.
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}`)
})
to run server.js, type in the command terminal:
node server.js
via mahmoud fathy
No comments:
Post a Comment