我正在使用资源组,并使用此过滤器来解决TokenMismatchException问题:
Route::filter('csrf',function($route,$request) {
if (strtoupper($request -> getmethod()) === 'GET') {
return;
// get requests are not CSRF protected
}
$token = $request -> ajax() ? $request -> header('X-CSRF-Token') : Input::get('_token');
if (Session::token() != $token) {
throw new Illuminate\Session\TokenMismatchException;
}
});
我的路线:
Route::group(array('prefix'=> 'admin','before' => 'csrf'),function(){
Route::resource('profile','ProfileController',array('as'=>'profile') );
});
现在。我收到Ajax请求的错误,如这段代码:
<script type="text/javascript">
$(document).ready(function() {
$('#frm').submit(function(e){
e.preventDefault();
name = $('#name').val();
family = $('#family').val();
email = $('#email').val();
currPassword = $('#currPassword').val();
password = $('#password').val();
password_confirmation = $('#password_confirmation').val();
$.post("{{ route('admin.profile.update',$profile->id) }}",{
_method : 'PUT',name : name,family : family,email : email,currPassword : currPassword,password : password,password_confirmation : password_confirmation
},function(data)
{
alert(data.errors.name);
},'json');
return false;
});
});
</script>
错误:
{"error":{"type":"Illuminate\\Session\\TokenMismatchException","message":"","file":"\/var\/www\/alachiq\/app\/filters.PHP","line":83}}
我想我必须在_ .post中发送_token。但是我不能使用name属性获取输入标签。 iget这个错误:
TypeError: 'stepUp' called on an object that does not implement interface HTMLInputElement.
在Laravel的文档中有一个提示如何做到这一点。这可能在问题的时候可能不可用,但是我以为我会用一个答案更新它。
http://laravel.com/docs/master/routing#csrf-x-csrf-token
我已经从文档中测试了元标记方法,并使其工作。将以下元标记添加到全局模板中
<Meta name="csrf-token" content="{{ csrf_token() }}">
添加此JavaScript,为jQuery中的所有ajax请求设置默认值。最好在您的应用程序中包含的js文件中。
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('Meta[name="csrf-token"]').attr('content')
}
})
该令牌可以存在于请求头或表单中。这将填充到每个ajax请求的请求头中。