giovanni_ giovanni_ - 1 month ago 17
Node.js Question

Server with Nodejs and client with XMLHttpRequest

I have this server.js

var http = require('http');

const PORT = 8000;

http.createServer((req, res) => {
var msg = req.url.split('/')[1];
console.log('Recieved: ' + msg);
var html = '<h3>You sent: ' + msg + '</h3>';
res.writeHead(200, {"Content-Type": "text/html"});
res.write(html);
res.end();
if (msg == 'end') process.exit();
}).listen(PORT, () => {
console.log("Server listening on: %s", PORT);
});


and this client.html

<!DOCTYPE html>
<html>

<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
<textarea id="textArea" rows="4" cols="50"></textarea>
<br>
<button onclick=" document.getElementById('textArea').value = '' ">clear</button>
<button onclick="sendToServer(document.getElementById('textArea').value)">send</button>
<br>
<p id="display"></p>

<script>
function sendToServer(data) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8000/" + data, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("display").innerHTML = xhr.responseText;
}
};
xhr.send();
}
</script>
</body>

</html>


The server recieves the data from the client and print it on console.
But I have a problem when the server sends the html string to the client. The client doesn't recieve the html string from the server.

How can I solve this problem?

Thank you.

Answer

Looks like you have a problem with Access-Control-Allow-Origin

That is why - you have exception on client side

Try to replace this (on server script)

 res.writeHead(200, {"Content-Type": "text/html"});

to this

res.writeHead(200, {"Content-Type": "text/html", "Access-Control-Allow-Origin": "*"});