我正在 Laravel 之上构建一个 API。我想通过使用 Throttle
中间件来使用内置的速率限制功能。
问题是,当 throttle 中间件触发时,响应是:
// Response headers
Too Many Attempts.
我的 API 使用 JSON 格式的错误负载,如下所示:
// Response headers
{
"status": "error",
"error": {
"code": 404,
"message": "Resource not found."
}
}
让
Throttle
中间件以我需要的方式返回输出的最佳方法是什么? 最佳答案
制作您自己的 Shiny 中间件,通过原始扩展它,并覆盖您喜欢覆盖的方法。
$ php artisan make:middleware ThrottleRequests
打开 kernel.php 并删除(注释掉)原始中间件并添加您的。
节流请求.php
<?php
namespace App\Http\Middleware;
use Closure;
class ThrottleRequests extends \Illuminate\Routing\Middleware\ThrottleRequests
{
protected function buildResponse($key, $maxAttempts)
{
return parent::buildResponse($key, $maxAttempts); // TODO: Change the autogenerated stub
}
}
内核文件
.
.
.
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
//'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
//'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'throttle' => \App\Http\Middleware\ThrottleRequests::class
];