Episode 10 of 12

GET, POST & DELETE Requests

Learn how to handle GET, POST, and DELETE requests to create, read, and delete data using Express and MongoDB.

Now let's build a full CRUD flow — creating, reading, and deleting blog posts using Express routes and MongoDB.

Handling GET Requests

const Blog = require('./models/blog');

// Get all blogs
app.get('/blogs', (req, res) => {
    Blog.find().sort({ createdAt: -1 })
        .then(blogs => res.render('index', { blogs }))
        .catch(err => console.log(err));
});

// Get a single blog
app.get('/blogs/:id', (req, res) => {
    Blog.findById(req.params.id)
        .then(blog => res.render('details', { blog }))
        .catch(err => console.log(err));
});

Handling POST Requests

First, add middleware to parse form data:

app.use(express.urlencoded({ extended: true }));
// Create a new blog
app.post('/blogs', (req, res) => {
    const blog = new Blog(req.body);
    blog.save()
        .then(() => res.redirect('/blogs'))
        .catch(err => console.log(err));
});

Handling DELETE Requests

HTML forms only support GET and POST. For DELETE, we use JavaScript on the client side:

// Server-side route
app.delete('/blogs/:id', (req, res) => {
    Blog.findByIdAndDelete(req.params.id)
        .then(() => res.json({ redirect: '/blogs' }))
        .catch(err => console.log(err));
});
// Client-side JavaScript
const deleteBtn = document.querySelector('.delete');
deleteBtn.addEventListener('click', () => {
    const id = deleteBtn.dataset.id;

    fetch('/blogs/' + id, { method: 'DELETE' })
        .then(res => res.json())
        .then(data => window.location.href = data.redirect);
});

Route Parameters

The :id in /blogs/:id is a route parameter. Express captures it in req.params.id, letting you fetch specific resources from the database.