如何在不使用表单的情况下通过 ejs 模板向后端发送放置请求?

How can I send put request to backend through ejs template without using form?

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

一些想法的代码片段:

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>

我可以这样做吗?

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

相同

使用 javascript 函数获取,您可以使用 [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 link:

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

为了实现这一点,您需要使用一个名为“method-override”的 npm 模块。所以首先安装 method-override 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>