Laravel自帶csrf驗證放刨,使用post時千萬別忘了這東西!
錯誤:
1.在form中的post會提示 TokenMismatchException 。
2.在ajax中會提示 500錯誤。
正確使用:
- form post
只需要在form內(nèi)加上 <input type="hidden" name="_token" value="{{ csrf_token() }}">即可。
<form action="/hello" method="post">
<input type="submit" value="submit">
{{--表單csrf驗證--}}
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
- ajax post
提交前加上一個csrf頭。
ajax post例子參考[jquery ajax POST 例子詳解]逢勾。(http://www.cnblogs.com/bestsaler/archive/2010/04/08/1835508.html)
//html
<meta name="csrf-token" content="{{ csrf_token() }}">
//js
var url = 'http://' + window.location.host + '/hello';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'post',
url: addCommendURL,
success :function (data) {
console.log("good");
}
});
- 從csrf保護中移除url
找到并打開 App\Http\Middleware\VerifyCsrfToken 文件,添加要移除的url藐吮。
protected $except = [
‘/hello’,
'myfriends'
];
```