DEV Community

Rittwick Bhabak
Rittwick Bhabak

Posted on

Node.js Crash Course - Part 10 - Get, Post & Delete Requests

  • 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>
Enter fullscreen mode Exit fullscreen mode

app.js:

app.post('/save', (req, res) => {
    console.log(req.body);
}
Enter fullscreen mode Exit fullscreen mode

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) )
})
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)