Send data from NodeJS back to same html page after

2019-08-17 17:24发布

问题:

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.

回答1:

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 back datos.

Here's a simple example of how you can intercept the POST request on the client side:

document.querySelector('form').onsubmit = evt => {

  // don't submit the form via the default HTTP redirect
  evt.preventDefault();
  
  // get the form values
  const formData = {
    name1: document.querySelector('input[name=name1]').value,
    name2: document.querySelector('input[name=name2]').value
  }
  console.log('formData:', formData);
  
  // send the form encoded in JSON to your server
  fetch('https://your-domain.com/path/to/api', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify(formData),
  })
  
  // receive datos from the server
  .then(resp => resp.json())
  .then(datos => {/* do what you want here */})
  
  // catch potential errors
  .catch(err => console.log('an error happened: '+err));
  
}
<form>
  <input name="name1" value="value1">
  <input name="name2" value="value2">
  <button type="submit">Submit</button>
</form>

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 by res.send(datos).