如何通过ejs模板向后端发送put请求而不使用form?

问题描述 投票:0回答:2

我想知道是否可以通过单击 ejs 中的按钮向后端发送 put 请求? 就我而言,我只想发送一个“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>

我可以这样做吗?

jquery css node.js express ejs
2个回答
4
投票

这个问题确实很常见,但有一个非常简单的解决方案,在前端,你有一个函数

fetch
它与NodeJs中的
node-fetch
相同

使用

javascript
,function fetch您可以轻松地用
API
和其他方法请求
[GET, PUT, POST]

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 读取值,将其放入 data

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 模块。所以首先安装
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>
© www.soinside.com 2019 - 2024. All rights reserved.