Php laravel 7 api CSRF令牌在POST请求时不匹配
我只需要在/app/Http/Middleware/VerifyCsrfToken.php中向异常添加api/*路径,对吗Php laravel 7 api CSRF令牌在POST请求时不匹配,php,laravel,api,Php,Laravel,Api,我只需要在/app/Http/Middleware/VerifyCsrfToken.php中向异常添加api/*路径,对吗 <?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware; class VerifyCsrfToken extends Middleware { /** * The URIs that
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
//
'api/*',
];
}
您应该为api路由使用api.php
文件,因为默认情况下,在app/http/kernel.php
中不会检查csrf\u令牌中间件:
protected $middlewareGroups = [
'web' => [
...
\App\Http\Middleware\VerifyCsrfToken::class,
...
],
'api' => [
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
错误在于,您已经在routes/web.php
上定义了api路由,如果您想从根域使用/api
,那么就在routes/api.php
上创建api路由
路由/api.php:
Route::get('/test', function () {
return 'Hello World';
});
现在您可以通过http://127.0.0.1:8000/api/test
web.php
文件包含RouteServiceProvider放置在web中间件组中的路由,该组提供会话状态、CSRF
保护和cookie加密。如果您的应用程序不提供无状态的RESTful API,那么您的所有路由都很可能在web.php
文件中定义
api.php
文件包含RouteServiceProvider放置在api
中间件组中的路由,该组提供速率限制。这些路由是无状态的,因此通过这些路由进入应用程序的请求将通过令牌进行身份验证,并且将无法访问会话状态
请参阅官方文档您使用的是路由/web.php
还是路由/api.php
?路由/web.php
谢谢。必须在这里描述,我不知道。