簡體   English   中英

如何在沒有頁面重定向或表單刷新的情況下在節點 js 上發送 post 請求。 沒有防止違約

[英]How to send a post request on node js without there being a page redirect or form refresh. there is no preventdefault

我有一個到達此端點的 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,但我不想重定向/刷新同一頁面

當我嘗試解決方案時會發生這種情況

這會在一段時間后發生

由於這是瀏覽器特定的行為,因此必須在客戶端通過 JavaScript 完成並在表單中使用 prevent default ,請參見此處

如果您只是不想刷新到該特定頁面,您可以在 express 中進行重定向,因此在他們提交表單后,他們會被引導離開該頁面,請參閱此處

如果您不想重新加載頁面,那么您需要使用 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"
  >

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM