【问题标题】:Laravel 8 API Unauthorized Handler Not ShowingLaravel 8 API未经授权的处理程序未显示
【发布时间】:2022-11-14 06:48:25
【问题描述】:

我想在没有访问令牌的情况下访问端点时添加自定义响应。我将这行代码添加到我的 Handler.php

public function render($request, Exception $exception)
    {
        if ($exception instanceof AuthorizationException) {
            return response()->json([
                'message' => 'Unauthorized'
            ],401);
        }

        return parent::render($request, $exception);
    }

我没有收到 json 响应,而是在邮递员上收到了一个带有 500 错误代码的空白响应。我究竟做错了什么? 响应:

【问题讨论】:

  • 请务必在您的请求中发送正确的标头Content-Type: application/json
  • 我尝试在我的请求中添加 Content-Type: application/json 但响应仍然是空白的。 Handler.php 本身是否有任何问题?

标签: json laravel api postman


【解决方案1】:

我通过确保服务器的响应是 JSON 来解决这个问题。所以我制作了一个名为 ForceJsonResponse.php 的中间件文件。这是代码:

public function handle(Request $request, Closure $next)
    {
        $request->headers->set('Accept', 'application/json');
        return $next($request);
    }

在 $middleware 上的 Kernel.php 中将其注册为

AppHttpMiddlewareForceJsonResponse::class,

在 $routeMiddleware 中作为

'json.response' => AppHttpMiddlewareForceJsonResponse::class,

【讨论】:

    猜你喜欢
    • 2012-07-21
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多