I have been looking for a solution for this days ago... so basically I have 2 files: index.html and hellonode.js. Index.html has a div with text and a button that is supposed to make a request to hellonode.js when clicked. hellonode.js is supposed to receive requests and send a response to them.
hellonode.js:
var http= require('http');
function onRequest(request, response){
console.log("request has been received");
response.writeHead(200, {"Context-Type": "text/plain"});
response.write("<h1>response here!</h1>");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("server is running");
here is my index.html:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "hellonode.js", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">
<h2>content</h2>
</div>
<button type="button" onclick="loadXMLDoc()">Your response content should appear here</button>
</body>
</html>
Im using node js and a apache server (the binary version on Apachelounge.com), and put inside the htdocs folder those 2 files and then start my server, so when I access 192.168.0.102 from my other computers, I get the index.html screen. Everything is fine until here. When I click the button and send the request, the response that I receive is the entire javascript code of hellonode.js. Why is that happening? I have a feeling that my hellonode.js isnt even receiving my request, and that the index.html is just reading the hellonode's content and showing it istead of actually sending a request to it. Im new to this server-side stuff. Thanks.
response here!
` – CaffeineAddiction Aug 07 '16 at 00:48