view raw
giovanni_ giovanni_ - 7 months ago 51
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"});
if (msg == 'end') process.exit();
}).listen(PORT, () => {
console.log("Server listening on: %s", PORT);

and this client.html

<!DOCTYPE html>

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

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

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


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.


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": "*"});