In an HTML page called "history.html", I have a form with the POST method that I submit to NodeJS server to make some operations.
<form action="/history/find" method="POST">
some form stuff
</form>
This is the code on the server that receives the form and makes some operations:
router.post("/history/find", function (req, res) {
var fechaInicial = req.body.fechaInicial;
var fechaFinal = req.body.fechaFinal;
var contaminante = req.body.contaminante;
Comment.find(
{
"data.time.s": {
"$gte": fechaInicial,
"$lte": fechaFinal
}
},
{
[contaminante]: 1,
"data.time.s": 1,
"_id": 0
}, function (error, datos) {
res.send(datos);
});
});
The resulting output of this particular Find operation is an set of many JSON objects (they are not surrounded with square brackets like in an Array), in this example, I just put 2 of them:
{
"data": {
"iaqi": {
"co": {
"v": 3.2
}
},
"time": {
"s": "2019-05-14 12:00:00"
}
}
},
{
"data": {
"iaqi": {
"co": {
"v": 4.8
}
},
"time": {
"s": "2019-05-15 00:00:00"
}
}
}
What I need to achieve, is to somehow send back the variable datos that contains the above result, back to the same HTML where I submitted the form.
If I use the res.send(datos), what I get is the data itself represented on the browser. I need to get back to the HTML page but having the variable available to use it and perform other operations directly on the page.
I have been searching the web with no luck on how to do this.
Thank you very much to everyone that can help me with this.
You can't send data to an HTML page. HTML is a static file format and cannot receive data by itself. A server can, but not an HTML file.
What you can do however, is intercept your post request on the client side, send it to the client using XHR and receiving back the data on the client side again, then do whatever you want when the script receives
datos
. Basically everything happens between the JavaScript part of the page and the Node server that receives POST data and sends backdatos
.Here's a simple example of how you can intercept the POST request on the client side:
PS: The above snippet will fail with a network error because only the client-side script is present - there is nothing running at
https://your-domain.com/path/to/api
, but you already included the right server code in your question. Just end the server script byres.send(datos)
.