如何在不进行页面重定向或表单刷新的情况下在节点js上发送发布请求。没有preventdefault

时间:2019-11-27 01:48:38

标签: javascript html node.js express

我有一个到达此端点的HTML表单。它发送数据,但是发送数据后我不希望页面刷新。这可能吗?

我不确定最好的解决方案是什么,nodejs中没有preventdefault,但我不想重定向/刷新同一页面

const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");

const app = express();


app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static("public"));

const PORT = process.env.PORT || 5001;

app.get("/", (req, res) => {
  res.sendFile("index.html", { root: __dirname });
});

app.post("/rumi", (req, res) => {
  console.log(res.req.body);

  res.json({ status: "ok" });


});

app.get("/rumi", (req, res) => {
  res.sendFile("index2.html", { root: __dirname });
});

app.listen(PORT, () => {
  console.log(`app running on port ${PORT}`);
});


这是html:

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport"
        content="initial-scale=1.0, user-scalable=no" />
  <meta charset="UTF-8" />
  <title>Drawing Tools</title>

  <style type="text/css">
    #map,
    html,
    body {
      padding: 0;
      margin: 0;
      height: 100%;
    }

    #panel {
      width: 200px;
      font-family: Arial, sans-serif;
      font-size: 13px;
      float: right;
      margin: 10px;
    }

    #color-palette {
      clear: both;
    }

    .color-button {
      width: 14px;
      height: 14px;
      font-size: 0;
      margin: 2px;
      float: left;
      cursor: pointer;
    }

    #delete-button {
      margin-top: 5px;
    }
  </style>

  <script src="/js/script.js"></script>

  <script>
    function submitRumiForm(e) {
      e.preventDefault();
      var formData = new FormData(document.getElementById("rumiForm"));
      var options = {
        body: formData,
        method: "POST"
      }
      fetch("/rumi", options).then(function(data) {
        console.log("post successful");
      }).catch(function(err) {
        console.log(err);
      })
    }

    var el = document.getElementById("stair-button")
    if (el) {
      el.addEventListener("click", submitRumiForm);
    }
  </script>
</head>

<body>
  <div id="panel">
    <div id="color-palette"></div>
    <div>
      <button id="delete-button">Delete Selected Shape</button>
      <button id="delete-all-button">Delete All Shapes</button>
    </div>
    <form id="rumiForm"
          action="/rumi"
          method="POST">
      <div>
        <h3>Elements</h3>
      </div>
      <button type="submit"
              name="stairs"
              value="clicked"
              id="stair-button"
              onclick="console.log('hi')">
        <img src="./images/stair.png" />
      </button>
      <button type="submit"
              name="ramp"
              value="clicked"
              id="ramp-button">
        <img src="./images/ramp.png" />
      </button>
      <button type="submit"
              name="exit"
              value="clicked"
              id="exit-button"><img src="./images/exit.png" /></button>
      <button type="submit"
              name="narrow"
              value="clicked"
              id="narrow-button">
        <img src="./images/narrow.png" />
      </button>
      <button type="submit"
              name="wide"
              value="clicked"
              id="wide-button"><img src="./images/wide.png" /></button>
      <button type="submit"
              name="construction"
              value="clicked"
              id="construction-button">
        <img src="./images/construction.png" />
      </button>
    </form>
  </div>
  <div id="map"></div>
</body>

</html>

我有一个到达此端点的HTML表单。它发送数据,但是发送数据后我不希望页面刷新。这可能吗?

我不确定最好的解决方案是什么,nodejs中没有preventdefault,但我不想重定向/刷新同一页面

This happens when i tried the solution

This happens after a while

2 个答案:

答案 0 :(得分:0)

由于这是特定于浏览器的行为,因此必须在客户端通过JavaScript进行使用,并在表单中使用prevent default,请参见here

如果您只是不想刷新到该特定页面,则可以使用express进行重定向,因此在他们提交表单后,他们将直接离开该表单,请参阅here

答案 1 :(得分:0)

如果您不想重新加载页面,则需要使用Ajax调用从浏览器发送带有Javascript的POST,而不是让浏览器自动发布表单。每当浏览器自动发布表单时,它将在浏览器窗口中显示表单响应。因此,如果您不希望这样做,则必须控制(在浏览器中)并使用自己的Javascript提交表单,这样就可以控制结果如何处理。

在表单中添加一个标识符:

<form id="rumiForm" action="/rumi" method="POST">

在HTML中的表单后添加此脚本

<script>

function submitRumiForm(e) {
   e.preventDefault();
   var formData = new FormData(document.getElementById("rumiForm"));
   var options = {body: formData, method: "POST"}
   fetch("/rumi", options).then(function(response) {
       return response.json();
   }).then(function(data) {
       // have the JSON response from the POST operation here
       console.log(data);
   }).catch(function(err) {
       console.log(err);
   })
}

document.getElementById("stair-button").addEventListener("click", submitRumiForm);

</script>

从此更改此表单项:

  <button type="submit"
          name="stairs"
          value="clicked"
          id="stair-button"
          onclick="console.log('hi')">

对此:

  <button type="submit"
          name="stairs"
          value="clicked"
          id="stair-button"
  >
相关问题