【问题标题】:How perform PATCH request from html form using NodeJS?如何使用 NodeJS 从 html 表单执行 PATCH 请求?
【发布时间】:2020-04-20 14:12:35
【问题描述】:

这是我尝试通过 NodeJS API 对从前端到 MongoDB 数据库的 HTML 表单执行补丁请求。

这是一个 Nodejs API 结构

app.route("/requests/:rollno")
  .get(function(req, res) {
// get method to find a query
  })
  .patch(function(req, res) {
    Request.update({
        rollno: req.params.rollno
      }, {
        $set:req.body
      },
      function(err) {
        if (!err) {
          res.send("Successfully updated requests");
        }else{
          res.send(err);
        }
      }
    );
  });
  

在表单的前端

<%- include('partials/header') %>
<h1>Recent requests</h1>
<% for(let i = 0; i < posts.length; i++) { %>
<article>
    <form action="/requests/21" method="PATCH">
      <input type="text" name="status[0]">
      <div id="participant"></div>
      <br>
      <button type="button" onclick="addParticipant()">Add</button>
      <button type="button" onclick="delParticipant()">Remove</button>
      <div class="btn-block">
        <button type="submit" href="/success">Submit Request</button>
      </div>
    </form>
</article>
<% } %>

表单实际上并未更新实际服务器上的信息。但是对于邮递员,数据正在更新。相同的最佳分辨率是什么,或者是否有任何替代方法?

【问题讨论】:

    标签: javascript html node.js mongodb forms


    【解决方案1】:
    <form action="/requests/B194057EP" method="PATCH">
    

    这是无效的,HTML 表单方法属性只支持 GET 和 POST 方法。 &lt;form method="put"&gt; 是无效的 HTML,将被视为 GET 请求。

    现在要解决这个问题,您可以利用 Jquery AJAX 将数据从客户端发送到您的后端。

    $.ajax({
        url: '<api url>',
        type: 'PATCH',
        data: {
            data: sendData
        },
        success: function () {
        }
    })
    ;
    

    【讨论】:

      【解决方案2】:

      在 vanilla JS 中,您可以使用 Promise 以及 async/await 来做到这一点,这是它的一个基本示例。

      async patching() {
        const responseFlow = await fetch(URL, {
         method: "PATCH",
         headers: {  
          'Content-Type': 'application/json'
         },
         // The content to update
         body: JSON.stringify({
           name: "New name"
         })
       })
      }
      

      【讨论】:

        猜你喜欢
        • 2018-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-10
        • 2017-11-18
        • 2018-02-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多