Vuejs axios DELETE Request Example

In this tutorial you will learn how to send the delete request with vuejs axios. We will use the vuejs to learn the http delete request. We are with some best examples with different requirements just like simple axios post reuqest, with error handling, with async/await and set http headers

The HTTP DELETE method is used to delete a resource from the server. Unlike GET and HEAD requests, the DELETE requests may change the server state. Let’s check how to use axios DELETE request for deleting data in vuejs example tutorial.

1. Simple axios DELETE Request in Vue

This sends an HTTP DELETE request to the Reqres api which is a fake online REST api that includes a /api/products/:id route that responds to DELETE requests with a HTTP 204 response. When the response is received the vue component displays the status message ‘Delete successful’.

axios.delete(`http://127.0.0.1:8000/api/products/1`)
     .then(response => {
         console.log(response);
     });

2. DELETE request using axios in Vuex

We can use the delete reuqest in vuex something like below.

deleteProduct ({ commit, state }, { productId }) {
  return new Promise((resolve, reject) => {
    axios.delete(`http://127.0.0.1:8000/api/products/${productId}`).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

3. DELETE request using axios with async/await

This sends the same DELETE request from Vue using axios, but this version uses an async function and the await javascript expression to wait for the promises to return (instead of using the promise then() method as above).

methods: {
    async createProduct() {
        await axios.delete(`http://127.0.0.1:8000/api/products/${productId}`)
             .then(response => {
                 console.log(response);
             });
    }
}

4. DELETE request using axios with error handling

Getting error messages using axios delete request we need to add .catch in our request just like below.

methods: {
    createProduct() {
        axios.delete(`http://127.0.0.1:8000/api/products/${productId}`)
             .then(response => {
                 console.log();
             })
             .catch(function (error) {
                console.log(error.response)
             })
    }
}

5. DELETE request using axios with set HTTP headers

To set headers just like authorization or content-type we can add just like below example.

methods: {
    createProduct() {
        const headers = { 
            'Authorization': 'Bearer my-token',
            'Content-Type': 'application/json'
        };
        axios.delete(`http://127.0.0.1:8000/api/products/${productId}`, {headers})
             .then(response => {
                 console.log(response);
             })
             .catch(function (error) {
                console.log(error.response)
             })
    }
}

6. Axios Delete request with body and headers

WE can put headers and body in our delete requests as well.

methods: {
    createProduct() {
        const headers = { 
            'Authorization': 'Bearer my-token',
            'Content-Type': 'application/json'
        };
        axios.delete(`http://127.0.0.1:8000/api/products/${productId}`, {
                'Authorization': 'Bearer my-token',
                'Content-Type': 'application/json'
            },
            data: {
                source: source
             })
             .then(response => {
                 console.log(response);
             })
             .catch(function (error) {
                console.log(error.response)
             })
    }
}

Vuejs axios DELETE request full Example

Here is the full example of vue axios delete request..

<template>
    <div class="container">
        <h2 class="text-center">axios delete request</h2>
        <div class="row">
            <div class="col-md-12">
                <table class="table">
                    <thead>
                    <tr>
                        <th>#</th>
                        <th>Name</th>
                        <th>Description</th>
                        <th>Price</th>
                        <th>Actions</th>
                    </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(product, key) of products">
                            <td>{{ key+1 }}</td>
                            <td>{{ product.name }}</td>
                            <td>{{ product.description }}</td>
                            <td>{{ product.price }}</td>
                            <td>
                                <router-link class="btn btn-success btn-sm" :to="{ name: 'ProductEdit', params: { productId: product.id }}">Edit</router-link>
                                <button class="btn btn-danger btn-sm" @click="deleteProduct(product.id)">Delete</button>
                            </td>
                            <td>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                products: {}
            }
        },
        created() {
            this.getProducts();
        },
        methods: {
            getProducts() {
              this.axios.get('http://laravel-app.co/api/products')
                  .then(response => {
                      this.products = response.data;
                  });
            },
            deleteProduct(productId) {
                this.axios
                    .delete(`http://laravel-app.co/api/products/${productId}`)
                    .then(response => {
                        let i = this.products.map(data => data.id).indexOf(productId);
                        this.products.splice(i, 1)
                    });
            }
        }
    }
</script>

I hope axios Delete request example in vue is help you…

Leave a Comment