從laravel 5.3+開(kāi)始,API路徑被放入了routes/api.php中。我們絕大多數(shù)的路徑其實(shí)都會(huì)在web.php中定義,因?yàn)樵趙eb.php中定義的路徑默認(rèn)有CSRF保護(hù),而API路徑默認(rèn)沒(méi)有CSRF保護(hù)。在Laravel官網(wǎng)文檔中寫(xiě)到:
Any HTML forms pointing to POST, PUT, or DELETE routes that are defined in the web routes file should include a CSRF token field. Otherwise, the request will be rejected.
所以,請(qǐng)注意你頁(yè)面的表單中是否使用了POST、PUT或DELETE方法,如果有,并且你沒(méi)有在表單中添加相應(yīng)的CSRF token時(shí),你的請(qǐng)求將會(huì)失敗。
有時(shí)候,我們可能不想要CSRF保護(hù)。比如我們想使用第三方軟件測(cè)試表單提交,或者比如微信公眾號(hào)接口的開(kāi)發(fā)時(shí),當(dāng)微信服務(wù)器使用POST推送給我們消息時(shí),如果開(kāi)啟了CSRF保護(hù),那么請(qǐng)求肯定是失敗的。
在這樣的情況下,我們可以使用API路徑來(lái)取消CSRF保護(hù)。
我們有兩種辦法來(lái)定義API Routes。
第一種辦法:
將routes放進(jìn)VerifyCsrfToken這個(gè)middleware的$except數(shù)組里:
<?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier; class VerifyCsrfToken extends BaseVerifier { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ '/api/my-route', ]; }
以上middleware的位置在app/Http/Middleware文件夾中。
第二種方法:
將routes放進(jìn)api.php里:
<?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::middleware('auth:api')->get('/user', function (Request $request) { return $request->user(); }); Route::get('/wechat', 'WechatAPIController@some-method'); Route::post('/wechat', 'WechatAPIController@some-other-method'); api.php和web.php同處于routes文件夾下。
在api.php中添加的路徑,在訪問(wèn)時(shí),我們需要在路徑前,加上api/前綴:
http://my-web-site/api/wechat
好了,這樣一來(lái),我們就完成了API路徑的定義,或者換句話說(shuō),取消了路徑的CSRF保護(hù)。想要獲取更多laravel教程歡迎關(guān)注編程學(xué)習(xí)網(wǎng)
掃碼二維碼 獲取免費(fèi)視頻學(xué)習(xí)資料
- 本文固定鏈接: http://www.wangchenghua.com/post/8308/
- 轉(zhuǎn)載請(qǐng)注明:轉(zhuǎn)載必須在正文中標(biāo)注并保留原文鏈接
- 掃碼: 掃上方二維碼獲取免費(fèi)視頻資料