axios DELETE request with body in Nuxt.js

Viewed 1081

I have an app built with Nuxt.js. To get data from the API I use axios, namely @nuxtjs/axios. All request work fine but for the DELETE method.

My syntax is the following:

      async removeItemFromCart(productId) {
        const accessKey = await this.$store.dispatch('fetchUserAccessKey');
        try {
            this.$axios.delete(`/api/baskets/products?userAccessKey=${ accessKey }`, {
                data: {
                    productId: productId
                }
            })
        } catch (error) {
            console.log(error);
        }
    },

However, in the console I always get the following error: createError.js?2d83:16 Uncaught (in promise) Error: Request failed with status code 400

I tried to use params instead of data, but to no avail. What am I missing here?

1 Answers

It seems that there's an issue with axios: when you use delete method with body, it either doesn't include payload, or deletes Content-type: 'application/json' from headers. To solve the issue, I used .request instead of .delete (according to https://github.com/nuxt-community/axios-module/issues/419)

                this.$axios.request(`/api/baskets/products?userAccessKey=${ accessKey }`, {
                    data: {
                        productId: productId
                    },
                    method: 'delete'
                }).
Related