Laravel Lumen 确保 JSON 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37296654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:49:53  来源:igfitidea点击:

Laravel Lumen Ensure JSON response

phpjsonapilaravellumen

提问by John Fonseka

I am new to Laravel and to Lumen. I want to ensure I am always getting only a JSON object as output. How can I do this in Lumen?

我是 Laravel 和 Lumen 的新手。我想确保我总是只得到一个 JSON 对象作为输出。我怎样才能在 Lumen 中做到这一点?

I can get a JSON response using response()->json($response);. But when an error happens, API giving me text/htmlerrors. But I want only application/jsonresponses.

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

Thanks in advance.

提前致谢。

回答by Wader

You'll need to adjust your exception handler (app/Exceptions/Handler.php) to return the response you want.

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

This is a very basic example of what can be done.

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

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

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

回答by MTVS

A more accurate solution based on @Wader's answer can be:

基于@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());
}

回答by xiscode

As MTVSanswer you could even use JsonResponse class to format your response, and use it as static member from within render method, not importing it in the Handler namespace like this:

作为MTVS答案,您甚至可以使用 JsonResponse 类来格式化您的响应,并将其用作渲染方法中的静态成员,而不是将其导入到 Handler 命名空间中,如下所示:

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 \Illuminate\Http\JsonResponse)
    {
        return $parentRender;
    }

    return new \Illuminate\Http\JsonResponse([
        'message' => $e instanceof HttpException
            ? $e->getMessage()
            : 'Server Error',
    ], $parentRender->status());
}