从Laravel 5.3+
开始,API
路径被放入了routes/api.php
中。我们绝大多数的路径其实都会在web.php
中定义,因为在web.php
中定义的路径默认有CSRF
保护,而API
路径默认没有CSRF
保护。在Laravel
官网文档中写到:
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.
所以,请注意你页面的表单中是否使用了POST
、PUT
或DELETE
方法,如果有,并且你没有在表单中添加相应的CSRF token
时,你的请求将会失败。
有时候,我们可能不想要CSRF
保护。比如我们想使用第三方软件测试表单提交,或者比如微信公众号接口的开发时,当微信服务器使用POST
推送给我们消息时,如果开启了CSRF
保护,那么请求肯定是失败的。
在这样的情况下,我们可以使用API
路径来取消CSRF
保护。
我们有两种办法来定义API Routes
。
第一种办法:
将
routes
放进VerifyCsrfToken
这个middleware
的$except
数组里:
<?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
放进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
中添加的路径,在访问时,我们需要在路径前,加上api/
前缀:
http://my-web-site/api/wechat
好了,这样一来,我们就完成了API
路径的定义,或者换句话说,取消了路径的CSRF
保护。