0

I am trying to get data from the back end Node server from the front end using a POST request but the HTML doesn't seem to catch and display the data properly. I've tested the backend using Postmaster and the data comes out fine. Can anyone help me out here? As the project complete code is kinda huge, I'll add the relevant snippet for now.

Backend is :

#!/usr/bin/env node

app.post('/data', urlencodedParser, function(req, res) {
    //config = DB auth data

    var pool = new pg.Pool(config);

    pool.query('SELECT url FROM imgs WHERE uid=$1 OR uid=0', [usid], function(err, result) {
      if (err) {
        console.log(err);
        res.status(400).send(err);
      }
      imgs = JSON.stringify(result.rows);

      res.send(imgs);
    });
    // Rest of the code ...
  }
});
<html>

<body>
  <button type="button" onclick="server()">submit</button>
  <p id="demo"></p>
  <script>
    function server() {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("demo").innerHTML =
            this.responseText;
        }
      };
      xhttp.open("POST", "http://localhost:8000/data", true);
      xhttp.send();
    }
  </script>

</body>

</html>

UPDATE : Turns out I need CORS to make this work. Thanks everyone for helping me out and @Quentin for finding what I was missing.

HariShyam
  • 1
  • 1
  • What is the response while making XmlHttp request? can you logged response? – Sandeep Patel Jul 24 '18 at 08:39
  • Use the developer tools in your browser. Look at the Network tab. Is the request made? Does it get the response you expect? Look at the Console. Are there any error messages? – Quentin Jul 24 '18 at 08:41
  • Dollars to donuts this is going to turn out to be a duplicate of https://stackoverflow.com/a/35553666/19068 – Quentin Jul 24 '18 at 08:42
  • @Quentin Yes, I didn't know browsers had such tools. Turns out I need CORS to allow complete access to the server with no hindrance. Thanks for your help. – HariShyam Jul 24 '18 at 09:06

1 Answers1

-1

Try using Jquery,

In your backend, your xhttp request can be replaced as below :

function server() { var body = {"name":"Bob"}; //whatever data you want to pass to the post request

$.ajax({ type: "POST", url: 'http://localhost:8000/data', data: JSON.stringify(body), success: function(result) { console.log(result); }, contentType: 'application/json' }); }