Skip to content
Advertisement

Cannot pass a personilized header with axios

I hava an application doing a CRUD, but when i try to use the method delete, i keep getting a 406 (Not Acceptable), I’m using an API formated in json_api, so i need personalized headers, in all other methods its working, but only delete not.

My axios.js

import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:3000',
});

export default api;

My headers.js

import api from './axios';

const authHeader = {
  headers: {
    Accept: 'application/vnd.api+json',
    'content-type': 'application/vnd.api+json',
  },
};

const body = {
  body: {
    name: 'Vitor Queiroz',
  },
};

async function getAuth() {
  return api.post('/auths', body, authHeader).then((response) => {
    return response.data.token;
  });
}

const headers = {
  headers: {
    Accept: 'application/vnd.api+json',
    'content-type': 'application/vnd.api+json',
    authorization: `Bearer ${await getAuth()}`,
  },
};

export default headers;

And my editUnit.vue

<template>
  <form action="">
    <label for="name">Nome da Unidade de Medida</label>
    <input type="text" v-model="name" />
    <br />
    <button type="submit" @click.prevent="editUnit(id)">Editar</button>
    <button type="submit" @click.prevent="deleteUnit(id)">Excluir</button>
    <div v-if="status === '200'">
      <p>Unidade de Medida Atualizada com Sucesso</p>
    </div>
    <div v-else-if="status === '204'">
      <p>Unidade de Medida Excluida com sucesso</p>
    </div>
    <div v-else-if="status !== '201' && status !== '' && status !== '204'">
      <p>Ocorreu um erro {{ this.error }} inesperado, tente novamente.</p>
    </div>
  </form>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
import api from '../../services/axios.js';
import headers from '../../services/headers.js';

export default defineComponent({
  name: 'createUnits',
  props: {
    id: {
      type: String,
    },
  },
  data() {
    return {
      myList: '',
      name: '',
      status: '',
      error: '',
      aaa: this.id,
    };
  },
  beforeMount() {
    api.get(`/units/${this.aaa}`, headers).then((res) => {
      this.myList = res.data.data;
      this.name = this.myList.attributes.name;
    });
  },
  methods: {
    editUnit(id) {
      const body = {
        id: `${id}`,
        name: `${this.name}`,
      };
      api
        .patch(`/units/${id}`, body, headers)
        .then((res) => {
          if (res.status == 200) {
            this.status = '200';
          }
        })
        .catch(
          (err) => (
            (this.error = err.response.status),
            (this.status = err.response.status)
          )
        );
    },

    deleteUnit(id) {
      const body = {
        id: `${id}`,
      };
      api
        .delete(`/units/${id}`, { data: { headers } })
        .then((res) => {
          console.log(id);
          if (res.status == 204) {
            this.status = '204';
          }
        })
        .catch(
          (err) => (
            (this.error = err.response.status),
            (this.status = err.response.status)
          )
        );
    },
  },
});
</script>

<style scoped></style>

The code referent to the delete method is between line 68-86

And my error in the api terminal is:

Started DELETE "/units/7" for 127.0.0.1 at 2022-08-16 15:02:33 -0300
Processing by UnitsController#destroy as HTML
Parameters: {"id"=>"7"}
Filter chain halted as :ensure_json_request rendered or redirected
Completed 406 Not Acceptable in 0ms (Views: 0.1ms | ActiveRecord: 0.0ms | Allocations: 87)

EDIT: enter image description here

Advertisement

Answer

The delete function is not correct

deleteUnit(id) {
    const body = {
      id: `${id}`,
    };
    api
      .delete(`/units/${id}`, { headers })
      .then((res) => {
        console.log(id);
        if (res.status == 204) {
          this.status = '204';
        }
      })
      .catch(
        (err) => (
          (this.error = err.response.status),
          (this.status = err.response.status)
        )
      );
  }
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement