Reputation: 27
This was my attempt to perform a patch request on an HTML form from the frontend to MongoDB database via NodeJS API.
This is a Nodejs API structure
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);
}
}
);
});
On the frontend side of the form
<%- 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>
<% } %>
The form is not actually updating the information on the actual server. But with the postman, the data is getting updated.What's the best resolution for the same or is there any alternate method for the same ?
Upvotes: 2
Views: 3377
Reputation: 11
You can use method override from NPM. Here is the link to the method override package.
First, you need to:
npm i method-override
var methodOverride = require('method-override')
app.use(methodOverride('_method'))
<form action="/requests/21?_method=Patch" method="post">
Upvotes: 1
Reputation: 91
In vanilla JS, you can use promises, as well as async/await to do so, this is a basic example of it.
async patching() {
const responseFlow = await fetch(URL, {
method: "PATCH",
headers: {
'Content-Type': 'application/json'
},
// The content to update
body: JSON.stringify({
name: "New name"
})
})
}
Upvotes: 0
Reputation: 335
<form action="/requests/B194057EP" method="PATCH">
This is invalid, HTML forms method attribute only supports GET and POST method. <form method="put">
is invalid HTML and will be treated like a GET request.
Now to solve this, you can make use of Jquery AJAX to send data from the client-side to your backend.
$.ajax({
url: '<api url>',
type: 'PATCH',
data: {
data: sendData
},
success: function () {
}
})
;
Upvotes: 2