Laravel-当API路由错误或找不到时如何显示JSON?

时间:2018-11-13 10:44:36

标签: json laravel api

我正在使用Laravel创建API,而邮递员正在检查我的API。当我在邮递员中输入正确的URL时,它工作正常,但是当我输入错误的URL时,它显示HTML和Laravel 404错误,我想返回JSON格式的消息,我该怎么做。

2 个答案:

答案 0 :(得分:3)

您应将Accept标头设置为application/json到标头标签中的邮递员请求中,如下所示::

Postman screenshot

这将告诉Laravel您需要json响应,而不是HTML。同样的方法也适用于您的应用程序内的任何请求。

如您所见,在Illuminate\Http\Response对象上对此进行了检查,设置了有效负载后,它将检查是否应将其变形为JSON:

/**
 * Set the content on the response.
 *
 * @param  mixed  $content
 * @return $this
 */
public function setContent($content)
{
    $this->original = $content;

    // If the content is "JSONable" we will set the appropriate header and convert
    // the content to JSON. This is useful when returning something like models
    // from routes that will be automatically transformed to their JSON form.
    if ($this->shouldBeJson($content)) {
        $this->header('Content-Type', 'application/json');

        $content = $this->morphToJson($content);
    }

    // If this content implements the "Renderable" interface then we will call the
    // render method on the object so we will avoid any "__toString" exceptions
    // that might be thrown and have their errors obscured by PHP's handling.
    elseif ($content instanceof Renderable) {
        $content = $content->render();
    }

    parent::setContent($content);

    return $this;
}

您可以找到代码here

希望这对您有所帮助。

答案 1 :(得分:0)

我了解OP的要求,因此希望将Not Found异常呈现行为覆盖为JSON响应。

Laravel实际上生成了exception类型的NotFoundHttpExceptionrender类型的 /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { // comment this line and return JSON Response. //return parent::render($request, $exception); return json_encode(array("message" => $exception->getMessage())); // or you can } 。要防止这种行为,您可以这样做。

在“ app \ Exceptions \ Handler.php”中,您看到一个函数

JSON

PS:这不是最终的解决方案,如果您仅想让API在发生错误的情况下返回IEnumerable,则只是一种解决方法。