这是我尝试通过 NodeJS API 对 HTML 表单从前端到 MongoDB 数据库执行补丁请求。
这是一个 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>
<% } %>
该表单实际上并未更新实际服务器上的信息。但是通过邮递员,数据正在更新。相同的最佳解决方案是什么,或者是否有其他替代方法?
<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 () {
}
})
;
在 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"
})
})
}
您可以在 npm 上使用方法覆盖,这里是方法覆盖包的链接,因此在您的代码中您基本上可以使用它https://www.npmjs.com/package/method-override
首先你需要做什么
<form action="/requests/21?_method=Patch" method="post">