Search code examples
javascriptnode.jsexpressxmlhttprequest

XmlHttpRequest to nodejs


I'm trying to send XMLHttpRequest from client side js to my node server. But nothing is happening. I'm quite new to this stuff. This is my function in javascript.

function sendTokenToServer(token) {
var xhttp = new XMLHttpRequest();  
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
   // document.getElementById("demo").innerHTML = xhttp.responseText;
   console.log(xhttp.responseText);
} 
xhttp.open("GET","http://localhost:3000/", true);
xtthp.send();
};
}

And this is my route in node js

    app.get('/fcm', function(req, res) {

      console.log('here');
      res.end('hee');
    });

Solution

  • You aren't making a request to the endpoint you created, you are requesting the route: / (which may or may not exist). Change the request to

     xhttp.open("GET","http://localhost:3000/fcm", true);
    

    And it should work (assuming your webpage and the server are running on the same port, otherwise you could run into CORS issues).