Laravel 5.4 TokenMismatchException Ajax调用

时间:2018-10-09 11:38:05

标签: ajax laravel laravel-5 csrf

仅当我使用ajax调用提交表单时,我才收到TokenMismatchException错误吗?如果我不使用Ajax调用,就不会收到错误消息。

是什么原因造成的?

Laravel 5.4

我在app.blade.php的头上有这个名字:

<meta name="csrf-token" content="{{ csrf_token() }}">

我的ajax.js

$( document ).ready(function() {
    // storing comments
    $('#storeComment').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
            method: 'POST',
            url: '/comments',
            data: {},
            success: function(response){
                console.log(response);
            },
            error: function(jqXHR, textStatus, errorThrown) { 
                console.log(JSON.stringify(jqXHR));
                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
            }
        });
    });
});

我还使用bootstrap.js来自动在Axios HTTP库中注册csrf-token元标记的值。如Laravel文档中所述。

控制方法:

public function store(CommentRequest $request)
{
    $comment = Auth::user()->comments()->save(new Comment($request->all()));

    $response = array(
        'status' => 'success',
        'comment' => $comment
    );

    return response()->json($response);
}

5 个答案:

答案 0 :(得分:1)

将令牌添加到ajax的数据中:

$.ajax({
type: 'POST',
 ......
data: {'_token': '{{ csrf_token() }}'},
........

答案 1 :(得分:1)

您可以直接调用jQuery并使用以下代码来代替Axios,而无需调用automatic csrf injection

var data = ['name' => 'Nikola', 'lastName' => 'Gavric'];
axios.post('/comments', data).then(function(response) {
    console.log(response);
});

编辑:axios的完整示例是

$('#storeComment').on('submit', function(e) {
    e.preventDefault();

    // Retrieve form data
    var temp = [];
    var data = $(this).serializeArray();
    $.each(data, function(index, field) {
        temp[field.name] = field.value;
    });

    // Post request with temp as data
    axios.post('/comments', temp).then(function(data) {
        console.log(data); 
    });
});

这是jQuery的代码,请使用您更喜欢的任何一种方法:

    $.ajax({
        method: 'POST',
        url: '/comments',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        data: {
            'name': 'Nikola',
            'lastName': 'Gavric'
        },
        success: function(response){
            console.log(response);
        },
        error: function(jqXHR, textStatus, errorThrown) { 
            console.log(JSON.stringify(jqXHR));
            console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
        }
    });

答案 2 :(得分:0)

$.ajax({
          type: 'POST',
          ........
            headers: {
                 'X-CSRF-TOKEN': '{{ csrf_token() }}'
           }    
         ...........
  });

尝试一下...

答案 3 :(得分:0)

csrf-token添加到应用程序的开头:

<meta name="csrf-token" content="{{ csrf_token() }}">

然后:

$.ajax({
  url: '/some/url',
  type: 'POST',
  headers: {
    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
  },
  success: function(res){
      // Your result
      console.log(res);
  }
});

答案 4 :(得分:-1)

您可以尝试在App\Http\Middleware\VerifyCsrfToken.php

中的特定路由上禁用CSRF验证
 protected $except = ['/comments'];