Laravel + Vue-删除对象,但控制台返回错误

时间:2018-10-17 12:03:29

标签: laravel vue.js

我正在尝试成功删除Vue中的记录。它会删除记录,但是在控制台中出现以下错误。

  

405(不允许使用方法)

我在“网络”标签中看到此错误

  

“例外”:“ Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException”,

这是在我的.vue文件中。

  <button @click="deletePet(pet.id)">Delete</button>

这是我的js文件

methods: {
    deletePet(id){

        var petid = id;

        window.axios.delete('/client/pet/' + id)
        .then(response => this.onSubmitSuccess(response))
        .catch(error => this.onSubmitError(error));;

        console.log('Pet Id' + petid);
      }
    },

这是我的幼虫路线

Route::delete('/client/pet/{id}', 'ClientController@deletePet')->name('client.pet.delete');

这是我在clientcontroller中的方法

public function deletePet($id){
      $pet = Pet::find($id);
      $pet->delete();

      return back();
    }

1 个答案:

答案 0 :(得分:0)

<html>
    <head>
        <script>
        // rename myToken as you like
        window.myToken =  <?php echo json_encode([
            'csrfToken' => csrf_token(),
        ]); ?>
        </script>
    </head>

添加通用标头:

 <script>
    window.axios.defaults.headers.common = {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-TOKEN' :  window.myToken 
    };
</script>

在您的方法中

methods: {
    deletePet(id){

        var petid = id;

        window.axios.delete('/client/pet/', {params:{'id': petid})
        .then(response => this.onSubmitSuccess(response))
        .catch(error => this.onSubmitError(error));;

        console.log('Pet Id' + petid);
      }
    },

laravel路线:

Route::delete('client/pet/{id}', 'ClientController@deletePet')->name('client.pet.delete');