I'm trying to build a REST API with NodeJs and Express (I'm a very beginner in programming), the CRUD requests work fine in Postman, but now I don't know how to send a DELETE request through a form with AJAX. I just want insert an id the text input and submit it to the server to delete a document in MongoDB. I searched everywhere but I could not understand how to perform this.
App.js
app.delete('/delete/:id', (req, res) => {
let id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(400).send();
}
Blog.findByIdAndRemove(id).then((docs) => {
res.status(200).send({docs})
}).catch((e) => {
res.status(400)
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Titolo</title>
</head>
<body>
<form action='/delete/:id' method="POST">
<input id="id" type="text" name="id" /><br />
<button id:"cancella" type="submit">Submit</button>
</form>
<script src="/js/jquery.js"></script>
<script src="/js/script.js"></script>
</body>
</html>
script.js
$(document).ready(function() {
$('#cancella').on("click", function() {
var id = $('#id').val();
$.ajax({
url: '/delete/:id',
type: 'DELETE',
data: {"id": id},
dataType: 'json',
success: function(data) {
//do something
}});
});
});