Laravel和ajax删除请求上的TokenMismatchException

问题描述:

我尝试使deleteajax发生请求。问题是我总是得到TokenMismatchException,即使我添加X-CSRF-TOKEN来请求标题。所以,有什么想法我做错了?下面是我的要求Laravel和ajax删除请求上的TokenMismatchException

$('#confirm-delete').click(function() { 
     if(tableRowId !== -1) { 
      var obj = { 
       "X-CSRF-TOKEN": $('meta[name=csrf-token]').attr('content'), 
       id: tableRowId 
      }; 
      $.ajax({ 
       headers: {'X-CSRF-TOKEN': $('meta[name=csrf-token]').attr('content')}, 
       url: 'sarasas/destroy', 
       method: 'DELETE', // Type of response and matches what we said in the route 
       data: obj, 
       success: function(response) { // What to do if we succeed 
        location.reload(); 
       }, 
       error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail 
        console.log(JSON.stringify(jqXHR)); 
        console.log("AJAX error: " + textStatus + ' : ' + errorThrown); 
       } 
      }); 
      tableRowId = -1; 
     } 
    }); 

改变这一点:

"X-CSRF-TOKEN": $('meta[name=csrf-token]').attr('content'), 

"_token": $('meta[name=csrf-token]').attr('content'), 

,或者如果它不工作添加这个JavaScript,设置默认为jQuery的所有Ajax请求。最好在包含在你的应用程序一个js文件:

$.ajaxSetup({ 
    headers: { 
     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
    } 
}) 

CSRF令牌鉴于head节就像名字添加meta标签,

<!DOCTYPE html> 
<html> 
<head> 
    <title></title> 
    <meta name="csrf-token" content="{{ csrf_token() }}"> 
    ....... 

然后添加以下代码的JS文件。

$.ajaxSetup({ 
    headers: { 
     'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 
    } 
    });