提交表单后将数据从 NodeJS 发送回相同的 html 页面

Send data from NodeJS back to same html page after form submission

在名为 "history.html" 的 HTML 页面中,我有一个带有 POST 方法的表单,我将其提交给 NodeJS 服务器以进行一些操作。

<form action="/history/find" method="POST">

some form stuff

</form>

这是服务器上接收表单并进行一些操作的代码:

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);

        });

});

这个特定的 Find 操作的结果输出是一组许多 JSON 对象(它们不像在数组中那样被方括号包围),在这个例如,我只放了其中的 2 个:

    {
        "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"
            }
        }
    }

我需要实现的是,以某种方式将包含上述结果的变量 datos 发送回我提交表单的相同 HTML。

如果我使用 res.send(datos),我得到的是浏览器上表示的数据本身。我需要返回到 HTML 页面,但要有可用的变量才能直接在页面上使用它并执行其他操作。

我一直在网上搜索,但没有找到如何执行此操作的方法。
非常感谢所有可以帮助我的人。

您不能向HTML页面发送数据。 HTML是一种静态文件格式,它本身不能接收数据。服务器可以,但 HTML 文件不可以。

然而,你可以做的是在客户端拦截你的 post 请求,使用 XHR 将其发送到客户端并再次在客户端接收回数据,然后做任何事情您希望脚本收到 datos 时。基本上一切都发生在页面的 JavaScript 部分和接收 POST 数据并发回 datos.

的节点服务器之间

这里有一个简单的例子,说明如何在客户端拦截 POST 请求:

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:上面的代码片段将因网络错误而失败,因为只有 client-side 脚本存在 - https://your-domain.com/path/to/api 上没有任何内容 运行,但您已经在您的问题中包含正确的服务器代码。只需按 res.send(datos).

结束服务器脚本