问题
I have analyze that ratio of getting Token Mismatch Error is very high. And this error getting because of some of the silly mistakes. There are many reasons developers are doing mistakes. Here are some of the examples.
- Not sending
_token
on header. - Not sending
_token
on data when using ajax. - Not Permission on Storage Path.
- Invalid Session Storage path.
And there many other reasons, feel free to edit this question for more more ways to prevent this type of error.
回答1:
Possible Change - 1
Setup Token on Header
Set the token on <head>
of your default.blade.php
view
<meta name="csrf-token" content="{{csrf_token()}}">
Add ajaxSetup
on the top of your script, that will be accessible to everywhere. This will set headers on each ajax call
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Set Token on <form>
tag
Add below function to your <form>
tag. This function will generate a hidden field named _token
and filled value with token
{{csrf_field()}}
Add csrf_token()
function to your hidden _token
in value attribute. This will generate only encrypted string.
<input type="hidden" name="_token" value="{{csrf_token()}}"/>
.
Possible Change - 2
Check session storage path & Permission
Here assume that project app url is APP_URL=http://project.dev/ts/toys-store
- Set the write permission to
storage_path('framework/sessions')
- Check the path of your laravel project
'path' => '/ts/toys-store',
this path is root of your laravel project. Change the name of your cookie
'cookie' => 'toys-store',
return [ 'driver' => env('SESSION_DRIVER', 'file'), 'lifetime' => 120, 'expire_on_close' => false, 'encrypt' => false, 'files' => storage_path('framework/sessions'), 'connection' => null, 'table' => 'sessions', 'lottery' => [2, 100], 'cookie' => 'toys-store', 'path' => '/ts/toys-store', 'domain' => null, 'secure' => false, 'http_only' => true, ];
Possible Change - 3
Use _token
field on AJAX
There are many ways to send _token
on AJAX call
- Get all input field's value within
<form>
tag usingvar formData = new FormData($("#cart-add")[0]);
- Use
$("#cart-add").serialize();
or$("#cart-add").serializeArray();
- Add
_token
manually on data of AJAX. using$('meta[name="csrf-token"]').attr('content')
or$('input[name="_token"]').val()
. We can set as header on a particular ajax call like below code.
$.ajax({ url: "path/to/ajax", type: "POST", data: formData, processData: false, contentType: false, dataType: "json", headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
来源:https://stackoverflow.com/questions/44819418/ways-to-prevent-tokenmismatch-exception-using-ajax-in-laravel