【问题标题】:How can I send put request to backend through ejs template without using form?如何在不使用表单的情况下通过 ejs 模板向后端发送 put 请求?
【发布时间】:2020-11-08 13:40:24
【问题描述】:

我想知道是否有在 ejs 中单击按钮时向后端发送放置请求? 在我的情况下,我只想向后端发送一个“id”,以便通过该 id 我可以更新数据库中的数据。 另外,是否每次都需要使用表单在 ejs 中向服务器发送 post/get 请求?或者还有其他可能的方法吗?

编码 sn-p 以获得一些想法:

ejs:

          <% if(user[i].complaint_type === "Bin Full"){ %>
            
          <form action="/assignCol" method="POST">
            <button
              name="id"
              value="<% user[i].id %>"
              type="submit"
              class="btn btn-info"
              style="margin-left: 630px;"
            >
              Assign collector
            </button>
          </form>

我可以这样做吗?

【问题讨论】:

    标签: jquery css node.js express ejs


    【解决方案1】:

    这个问题很常见,但有一个非常简单的解决方案,在前端,你有一个函数fetch,它与NodeJs中的node-fetch相同

    有了javascript,函数fetch你可以很容易地用[GET, PUT, POST]和其他方法请求API

    fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, *cors, same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
          'Content-Type': 'application/json'
          // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify(data) // body data type must match "Content-Type" header
      });
    

    您可以使用METHOD 传递许多参数,或者您可以简单地避免它们

    对你来说,这很容易工作:

    只需使用 javascript 函数从 form 中读取值,将其放入数据 JSON 变量中,然后使用此函数

    fetch(url, {
        method: 'PUT',
        body: JSON.stringify(data) 
        }
    

    记住这是异步函数,不要忘记使用await

    为了更好地理解,请访问此 MDN 链接:

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

    【讨论】:

      【解决方案2】:

      为了实现这一点,您需要使用一个名为“method-override”的 npm 模块。所以首先安装方法覆盖npm模块:

      npm i method-ovverride
      

      现在在您的 app.js 或 server.js 中添加以下内容以将方法覆盖配置为中间件:

      const methodOverride = require('method-override');
      
      
      app.use(methodOverride());
      

      现在您需要在 ejs 中的表单中提及,这会将数据传送到 PUT 路由,如下所示:

      <form action="/assignCol?_method=PUT" method="POST">
              <button
                name="id"
                value="<% user[i].id %>"
                type="submit"
                class="btn btn-info"
                style="margin-left: 630px;"
              >
                Assign collector
              </button>
      </form>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-24
        • 2020-05-04
        • 2018-02-13
        • 1970-01-01
        • 2012-06-19
        • 1970-01-01
        • 2017-07-30
        • 1970-01-01
        相关资源
        最近更新 更多