尝试使用放置axios提交数据,但不允许使用405方法

时间:2017-10-16 16:00:34

标签: jquery axios laravel-5.5

我正在尝试使用jquery代码中的PUT方法提交

  $('#mainTable td').on('change', function(evt, newValue) {
    var $put_method = $('#user-put-method input').val();
    var $name       = $(this).attr('id');
    var $url        = "<?php echo route('Profile.update', Auth::id()) ?>";
    var data        = {
      '__method': $put_method,
      'name': $name
    };

    axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
    axios.post($url, data)
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      });
  });

var $put_method = $('#user-put-method input').val();的数据源来自

<div class="" id="user-put-method">
  {{ method_field('PUT') }}
</div>

我有这个方法来捕获请求

public function update(Request $request, $id)
{
  d($request, $id);
}

并通过这条路线

Route::resource('Profile', 'UserProfileController');

但是当我看看chrome dev-tool时 我收到了这条消息

http://project.dev/Profile/1 405 method not allowed

有没有人遇到或做过类似我的问题?

1 个答案:

答案 0 :(得分:2)

在你的HTML头文件上添加这个脚本:

<script>
    window.Laravel = <?php echo json_encode([
        'csrfToken' => csrf_token(),
        'base_url'  => \URL::to('/'),
    ]); ?>
</script>

你的axios数据:

var data        = {
  '__method': $put_method,
  'name': $name,
  '_token': window.Laravel.csrfToken
}; 
// axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

  axios.put($url, data)
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
相关问题