Laravel post使用

Laravel自帶csrf驗(yàn)證,使用post時(shí)千萬(wàn)別忘了這東西!

錯(cuò)誤:
1.在form中的post會(huì)提示 TokenMismatchException 。


2.在ajax中會(huì)提示 500錯(cuò)誤。

正確使用:

  1. form post
    只需要在form內(nèi)加上 <input type="hidden" name="_token" value="{{ csrf_token() }}">即可。
<form action="/hello" method="post">
        <input type="submit" value="submit">
        {{--表單csrf驗(yàn)證--}}
        <input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
  1. ajax post
    提交前加上一個(gè)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");
    }
});
  1. 從csrf保護(hù)中移除url
    找到并打開 App\Http\Middleware\VerifyCsrfToken 文件,添加要移除的url。
protected $except = [
    ‘/hello’,
    'myfriends'
];
```
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容