- GET - requests to get a resource
- POST - Inserting a data
- DELETE - Deleting data from database
- PUT - Updating data in the database
Receiving form data in server:
form.html:
<form action="/save" method="POST">
<input name="title" type="text">
<input value="Save" type="submit">
</form>
app.js:
app.post('/save', (req, res) => {
console.log(req.body);
}
We also have to use app.use(express.urlencoded({ extended: true }));
to get the request body appropriatly.
deleting a post using fetch api
In app.js
app.delete('/blogs/:id', (req, res) => {
const id = req.params.id;
Blog.findByIdAndDelete(id)
.then( result=> res.json({ redirect:'/blogs' }))
.catch( err => console.log(err) )
})
In html:
<button id="trashcan" data-doc="<% blog._id %>">Delete</button>
<script>
const trashcan = document.getElementById('trashcan');
trashcan.addEventListener('click', (e)=>{
const endpoint = `/blogs/${trashcan.dataset.doc}`;
fetch(endpoint, {
method: 'DELETE'
})
.then( response => response.json() )
.then( data => window.location.href = data.redirect )
.catch( err => console.log(err) )
})
</script>
Top comments (0)