REST defines a set of conventions to create HTTP services. The basic four methods can create CRUD (Create, Read, Update, Delete)
• POST: Create a resource
• GET: Read a resource
• PUT: Update a resource
• DELETE: Delete a resource
In frontend side, you could do CRUD with form input as an example. The following is an example with POST. This case is pretty simple to run POST method only with HTML from front-end side.
///HTML Front-end:
{{<form action="/api" method="post">
<input type="text" class="form-control" name="text">
<button class="btn btn-default" type="submit">
</form>}}
/// NODE.JS Back-end:
router.post('/api', (req, res) => {
const todo = new Todo({
text: req.body.text,
completedAt: Date.now()
});
todo
.save()
.then(todos => res.redirect('/'))
.catch(err => res.status.send(err));
});
However, if you don't have form input or form input may take different types of methods within it, you may need to take a different approach such as AJAX.
The following is an example of AJAX. Combining HTML and AJAX is front-end operation while Node.JS with DB (e.g. MongoDB) is the backend operation.
(1) Take button click event and take attribute from 'data-id'.
(2) Run AJAX DELETE method. You should make sure that its Method and URL are correctly match between AJAX side and Node.JS + DB side.
(3) I was trying to redirect by using res.redirect('url') in back-end side, but it didn't work. I learned that you cannot send redirect response to AJAX call, but you should let the browser reload the page. "window.loaction.reload()" does the job here.
/// Front-end : HTML side:
<button class="btn-danger" id="delete-btn" data-id="{{this._id}}">X</button>
///Front-end: AJAX side;
$('.todo-list-group').on('click', '#delete-btn', function(event) {
event.preventDefault();
const id = $(this).attr('data-id');
$.ajax({
url: '/api/delete/' + id,
method: 'DELETE',
data: { id: id }
}).done(function(res) {
if (res.success) {
console.log('id from ajax call is', res);
window.location.reload();
} else {
console.log('error...ajax');
}
});
/// Back-end: Node.js + Mongoose (MongoDB)
router.delete('/api/delete/:id', (req, res) => {
Todo.deleteOne({ _id: req.params.id })
.then(() => {
res.json({ success: true });
})
.catch(err => {
res.status.json({ err: err });
});
});
Top comments (1)
Can you show the edit routes and ajax too with a button?