简体   繁体   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

I have an HTML form which hits this endpoint.我有一个到达此端点的 HTML 表单。 It sends data, but I don't want the page to refresh once sending the data.它发送数据,但我不希望页面在发送数据后刷新。 is this possible?这可能吗?

im not sure what the best solution is, there is no preventdefault in nodejs, but I don't want to redirect/refresh the same page我不确定最好的解决方案是什么,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}`);
});


Here is the html :这是 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>

I have an HTML form which hits this endpoint.我有一个到达此端点的 HTML 表单。 It sends data, but I don't want the page to refresh once sending the data.它发送数据,但我不希望页面在发送数据后刷新。 is this possible?这可能吗?

im not sure what the best solution is, there is no preventdefault in nodejs, but I don't want to redirect/refresh the same page我不确定最好的解决方案是什么,nodejs 中没有 preventdefault,但我不想重定向/刷新同一页面

This happens when i tried the solution当我尝试解决方案时会发生这种情况

This happens after a while这会在一段时间后发生

As this is browser specific behaviour, this has to be done on the client side via JavaScript & using prevent default with the form, see here .由于这是浏览器特定的行为,因此必须在客户端通过 JavaScript 完成并在表单中使用 prevent default ,请参见此处

If you simply don't want to refresh to that specific page, you can do a redirect in express, so after they submit the form, they are directed away from it, see here .如果您只是不想刷新到该特定页面,您可以在 express 中进行重定向,因此在他们提交表单后,他们会被引导离开该页面,请参阅此处

If you don't want the page to reload, then you need to send the POST with Javascript from the browser using an Ajax call rather than letting the browser post the form automaticallyl.如果您不想重新加载页面,那么您需要使用 Ajax 调用从浏览器发送带有 Javascript 的 POST,而不是让浏览器自动发布表单。 Anytime the browser posts the form automatically, it will display the form response in the browser window.每当浏览器自动发布表单时,它都会在浏览器窗口中显示表单响应。 So, if you don't want that, you have to take control (in the browser) and submit the form with your own Javascript so then you can control what happens with the result.因此,如果您不希望那样,您必须控制(在浏览器中)并使用您自己的 Javascript 提交表单,以便您可以控制结果发生的情况。

Add an identifier to your form:向表单添加标识符:

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

Add this script after the form in your HTML :在 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>

Change this form item from this:从此更改此表单项:

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

to this:对此:

  <button type="submit"
          name="stairs"
          value="clicked"
          id="stair-button"
  >

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM