CSRF Marker Failure | Laravel 5.4

Whenever I send a POST request to the server, a TokenMismatchException is thrown. I already tried to send

<input type="hidden" name="_token" value= "{{csrf_token()}}"> 

I used to use ajaxHeader to send this specific information to the server, but this also throws the same error.

I debugged more and found out what was in the VerifyCsrfToken file.

 protected function tokensMatch($request) { $token = $this->getTokenFromRequest($request); return is_string($request->session()->token()) && is_string($token) && hash_equals($request->session()->token(), $token); } array:3 [ "sessionToken" => "rgicYLOUhb2kLLChpVByNLQO1KVMb0Gkjzb7ZtTN" //$request->session()->token() "requestToken" => "IgXWquvnfujZJ1Vs9vbSgpjgX3rAnd5PpeklRvBD" // $request->input('_token') ?: $request->header('X-CSRF-TOKEN') "laravel_token" => "rgicYLOUhb2kLLChpVByNLQO1KVMb0Gkjzb7ZtTN" //csrf_token() ] 

I get a middleware token matching function over the array. Can someone tell me the reason and solution to this particular problem? Below is the ajax I'm using

 function likeReview(id) { var like_span = $('#like_'+id); var like_div = $('#likeDiv_'+id); var like_span_text = $('#likeText_'+id); $.ajax({ type: 'post', url: '{{route('like.review')}}', data: {review_id: id}, beforeSend: function () { }, success: function (data) { if(data.status == 'success') { var like = like_span.html(); var sum = 0; if(data.like == 1){ sum = parseInt(like)+1; like_div.addClass('upvoted-active'); like_span_text.html('UPVOTED'); } else { sum = parseInt(like)-1; like_div.removeClass('upvoted-active'); like_span_text.html('UPVOTE'); } like_span.html(sum); } }, error: function (xhr, textStatus, thrownError) { alert('Something went wrong. Please try again!'); } }); } 

The function is called by pressing the upvote button.

 <div class="js-btn-thank-area upvoted-active js-activity-root" id="likeDiv_{{$review->id}}"> <a href="javascript:;" onclick="likeReview({{$review->id}})" class="thank-btn"> <i class="fa fa-arrow-up fa-fw"></i> <span class="feed-action-text" id="likeText_{{$review->id}}">UPVOTED</span> </a> <div class="stats-thanks" id="like_{{$review->id}}"> {{$review->likes()->where('like','=',1)->count()}} </div> </div> 
+7
php laravel
source share
1 answer

Just using CSRF as a field for posting with AJAX does not work;

 $.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } }); 

Before making an ajax call, configure it :)!

EDIT . You can also put ajax in the data part of your request;

 data: { review_id: id, "_token": "{{ csrf_token() }}" } 

EDIT . To clarify the removal of temporary data from storage , this problem was solved in the chat.

+2
source share

All Articles