Laravel速率限制返回JSON有效负载

Cod*_*ith 3 php laravel laravel-5 laravel-5.3

我正在Laravel之上构建一个API.我想通过使用Throttle中间件来使用内置的速率限制功能.

问题是,当油门中间件触发响应时:

// Response headers
Too Many Attempts.
Run Code Online (Sandbox Code Playgroud)

我的API使用JSON中的错误有效内容,如下所示:

// Response headers
{
  "status": "error",
  "error": {
    "code": 404,
    "message": "Resource not found."
  }
}
Run Code Online (Sandbox Code Playgroud)

使Throttle中间件以我需要的方式返回输出的最佳方法是什么?

Kys*_*lik 8

制作自己的闪亮中间件,按原件扩展,并覆盖您想要覆盖的方法.

$ php artisan make:middleware ThrottleRequests
Run Code Online (Sandbox Code Playgroud)

打开kernel.php并删除(注释掉)原始中间件并添加你的.

ThrottleRequests.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
    }
}
Run Code Online (Sandbox Code Playgroud)

kernel.php

.
.
.
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
];
Run Code Online (Sandbox Code Playgroud)