Laravel Lumen确保JSON响应

Joh*_*eka 14 php api json laravel lumen

我是Laravel和Lumen的新手.我想确保我总是只获得一个JSON对象作为输出.我怎么能在流明这样做?

我可以使用JSON响应response()->json($response);.但是当发生错误时,API会给我text/html错误.但我只想application/json回复.

提前致谢.

Wad*_*der 35

您需要调整异常处理程序(app/Exceptions/Handler.php)以返回所需的响应.

这是可以做什么的一个非常基本的例子.

public function render($request, Exception $e)
{
    $rendered = parent::render($request, $e);

    return response()->json([
        'error' => [
            'code' => $rendered->getStatusCode(),
            'message' => $e->getMessage(),
        ]
    ], $rendered->getStatusCode());
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,此示例将始终返回 `200` HTTP 代码。你可能不想那样。例如,如果使用`findOrFail()`,`code` 元素将正确显示`404`,但整体结果仍将是`200`,显然不是。为了解决这个问题,将 `$rendered->getStatusCode()` 作为它的第二个参数传递给 `json()`。 (3认同)

MTV*_*TVS 8

基于@Wader答案的更准确的解决方案可以是:

use Illuminate\Http\JsonResponse;

public function render($request, Exception $e)
{
    $parentRender = parent::render($request, $e);

    // if parent returns a JsonResponse 
    // for example in case of a ValidationException 
    if ($parentRender instanceof JsonResponse)
    {
        return $parentRender;
    }

    return new JsonResponse([
        'message' => $e instanceof HttpException
            ? $e->getMessage()
            : 'Server Error',
    ], $parentRender->status());
}
Run Code Online (Sandbox Code Playgroud)

  • 很好的完整答案,包括必要的课程。给我点赞 (2认同)

Cés*_*ero 7

我建议您添加一个将Accept标头设置为application/json.

例如,您可以创建一个名为的中间件RequestsAcceptJson,并以这种方式定义它:

<?php

namespace App\Http\Middleware;

use Closure;

class RequestsAcceptJson
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $acceptHeader = strtolower($request->headers->get('accept'));

        // If the accept header is not set to application/json
        // We attach it and continue the request
        if ($acceptHeader !== 'application/json') {
            $request->headers->set('Accept', 'application/json');
        }

        return $next($request);
    }
}

Run Code Online (Sandbox Code Playgroud)

然后你只需要将它注册为一个全局中间件,以便在对你的 api 的每个请求中运行。在流明中,您可以通过在中间件调用中添加类来做到这一点bootstrap/app.php

$app->middleware([
    App\Http\Middleware\RequestsAcceptJson::class
]);
Run Code Online (Sandbox Code Playgroud)

对于 Laravel,它的过程几乎相同。现在错误处理程序将始终返回一个 json 而不是纯文本/html。