How to to handle token mismatch exception in laravel post ajax?

泄露秘密 提交于 2019-12-10 11:53:14

问题


In my Laravel 5.4, I use the following code in my ajax using jQuery:

            $.ajax({
                url     : 'http://example.com/addmember',
                method    : 'POST',
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                beforeSend  : function()
                {},
                data : $('#theForm').serialize(),
                success   : function(response)
                {
                   // I do something here
                },
                error : function(e)
                {
                    console.log(e);
                },
                complete : function(c){
                }
            });

I sometimes get a token mismatch exception like so: I generally get this error when the user stays on the page for a very long time before firing the AJAX request.

How can i handle the situation ?

I even made a middleware that upon a token mismatch on an ajax call returns a response like response.status == "TOKEN-ERROR" on getting this i reload the page using window.loaction.reload(1);.

Is there any more efficient method to handle the situation without reloading the page and thus loosing the user's progress ?


回答1:


In your app/Exceptions/Handler.php file

Add a handler for TokenMismatchException in the render method

public function render($request, Exception $exception)
{
    if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
        if ($request->expectsJson()) {
            return response()->json([
                'error' => 'Token mismatch'
            ], $exception->getStatusCode());
        };
    }

    return parent::render($request, $exception);
}

This will return an error json response. You can customize the error response to suit your needs.




回答2:


When I'm using an Ajax call, I add the _token attribute to the data:

$("input").on("someFunction", function(event) {
      var score = $(this).val();
      var scoreId = $(this).data('score-id');
      $("#" + scoreId).text(event.value);
      console.log(scoreId + ' => ' + score);
      var data = {
         "_token": "{{ csrf_token() }}",
         "score": score,
         "scoreId" : scoreId
      };
      $.ajax({
          data: data,
          type: "POST",
          url: '{!! route('score.store', $id) !!}',
          success: function (result) {
          console.log(result);
      },
      error: function (xhr, status, error) {
         var err = eval("(" + xhr.responseText + ")");
         alert(err.error);
      }
   });
});

In my web.php I add this item to the route:

 Route::post('/path/to/route/{id}/score/store', [
    'before' => 'csrf',
    'as' => 'score.store',
    'uses' => 'Score\ScoreController@saveScore'
 ]);


来源:https://stackoverflow.com/questions/44032792/how-to-to-handle-token-mismatch-exception-in-laravel-post-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!