【问题标题】:what is the role of api middleware in laravelapi中间件在laravel中的作用是什么
【发布时间】:2021-09-03 02:29:31
【问题描述】:

我有一个关于 laravel8 的简单问题

我测试了两个代码,但没有发现任何差异。它们对我来说看起来一样。即使我点击了很多时间,都给了我“太多的请求”。

Route::middleware('api')->get('/user', function (Request $request) {
    return "aaa";
});

Route::get('/user', function (Request $request) {
    return "aaa";
});

'throttle:api' 和 SubstitueBindings 的作用是什么?

    'api' => [
        'throttle:api',
        \Illuminate\Routing\Middleware\Substitu\Illuminate\Routing\Middleware\SubstituteBindings::classteBindings::class,
    ],

【问题讨论】:

  • 对于这样一个简单的调用,您第一眼看不出区别。下面的答案中有更多详细信息。

标签: laravel middleware throttling


【解决方案1】:

在同一文件kernel.php 中,您将找到web 请求的中间件,这是默认模式。

'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

所以web 用于有状态请求,带有会话、cookie、csrf 令牌、会话身份验证......

api 用于无状态请求,因此没有上述这些功能,而是使用另一个中间件 throttle 来限制每分钟 IP 的请求数(检查配置的限制,默认 60/百万)。

SubstituteBindings 对两者都是通用的,它处理路由声明中配置的参数的绑定。

通常,您不会将这两个堆叠在一起。要使用它们,请使用已经存在的文件 web.phpapi.php。这是如何运作的 ?查看App\Providers\RouteServiceProvider的内容

public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace) //the value here is \App\Http\Controllers
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });
    }

如果您的项目可以分成更多组,您可以编辑此文件。

例如,我曾经用它创建了 5 个不同的组,每个组都有自己的路由文件,因为我有 4 个不同的可验证实体(管理员、所有者、用户、审核...) ) 每个都有自己的命名空间(控制器基础命名空间)和自己的会话中间件

【讨论】:

    猜你喜欢
    • 2017-08-18
    • 2021-09-06
    • 1970-01-01
    • 2019-01-07
    • 2020-02-22
    • 2016-11-20
    • 2017-07-10
    • 2016-12-12
    • 1970-01-01
    相关资源
    最近更新 更多