laravel - laravel中api中间件的作用是什么

标签 laravel middleware throttling

我在 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,
    ],

最佳答案

在同一个文件 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 用于有状态请求,带有 session 、cookie、csrf token 、 session 身份验证...

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

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

通常,您不会将这两个堆叠在一起。要使用它们,请使用已存在的文件 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 个不同的组,每个组都有自己的路由文件,因为在公共(public)实体(网络)之上我有 4 个不同的可验证实体(管理员、所有者、用户、审核...) )每个都有自己的命名空间( Controller 基本命名空间)和自己的 session 中间件

关于laravel - laravel中api中间件的作用是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68033679/

相关文章:

php - 消息为 'Call to undefined method Illuminate\Database\Query\Builder::toArray()' 的 BadMethodCallException

laravel - @生产脚本失败。运行 npm run production 时出错

javascript - 为什么 expressjs 在空闲时为 PUT 生成 ERR_EMPTY_RESPONSE?

python - 使用多个代理限制请求

php - 问题 Integrity constraint violation : 1048 Column

laravel - 2 模型 2 foreach 在 1 个 View 中。拉维尔

node.js - 带有参数的 Jest Express 测试中间件

php - Laravel 在中间件中获取 {id} 获取参数

linux - Linux fq_codel 中的单独流程是什么?

javascript - 从一个事件监听器中触发两个函数(一个被限制,另一个没有)