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 node.js:
#!/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.