gpt4 book ai didi

javascript - 如何使用 NodeJS 从 html 表单执行 PATCH 请求?

转载 作者:行者123 更新时间:2023-11-30 19:00:36 24 4
gpt4 key购买 nike

这是我尝试通过 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>
<% } %>

表单实际上并没有更新实际服务器上的信息。但是对于 postman ,数据正在更新。相同的最佳解决方案是什么,或者是否有任何替代方法?

最佳答案

<form action="/requests/B194057EP" method="PATCH">

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

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

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

关于javascript - 如何使用 NodeJS 从 html 表单执行 PATCH 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com