0
<html>
<body>
    <script>
        function test(){
        alert("Inside test");
        var request = new XMLHttpRequest();
        request.open('GET', "http://localhost:8080/name.txt", true);
        request.onreadystatechange  = function(){
        alert(request.responseText);
    }
        request.send();
    }

    test();
    </script>
</body>
</html>

In the above code snippet, I am trying to send GET request to the local server which is hosted using node.js and it has an associated server js file to handle the request as below

var http = require('http');
var URL = require('url');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  var q = URL.pathname;
  res.end(q);
}).listen(8080);

I need to get the response data back to my function test and use it to display.But I am not able to do that.I can only output the response to the html page when I navigate to URI "http://localhost:8080/name.txt" manually. How do I achieve this from my code?

Gunacelan M
  • 179
  • 2
  • 10
  • what is the error ? – Dhananjai Pai Aug 04 '18 at 17:29
  • no error.I don't get the response text.It is empty.Will the *res.end(q)* add the data valueto the *responsetext* ? – Gunacelan M Aug 04 '18 at 17:31
  • Open the developer tools in your browser. Look at the Console. Read the error message there. – Quentin Aug 04 '18 at 17:32
  • You've shown us your server code, which clearly doesn't send the HTML in the first part of the question to the browser, so this *must* be a cross-origin request, hence closing as a duplicate. You'd have got there a lot sooner if you had looked at the Developer Tools Console and used a search engine to find out about the error message that will be reported there. – Quentin Aug 04 '18 at 17:34

0 Answers0