如何在laravel中返回json格式的响应而不是html

问题描述 投票:1回答:1

我正在使用一些API,并且无论何时未找到数据或未找到api,我都会收到以下类型错误:


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Not Found</title>
    ...
</head>

<body>
    <div class="flex-center position-ref full-height">
        <div class="code">
            404 </div>

        <div class="message" style="padding: 10px;">
            Not Found </div>
    </div>
</body>

</html>

如何获取JSON格式的同一内容?无需在应用的网络端修改这种响应的任何最佳方法!

json laravel api error-handling
1个回答
0
投票

您可以在App\Exceptions\Handler.php文件中执行以下操作,方法是扩展渲染功能,如下所示:>

public function render($request, Exception $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Nothing found dude.'], 404);
    }
    return parent::render($request, $exception);
}

->expectsJson方法响应HTTP标头

Accept: application/json
© www.soinside.com 2019 - 2024. All rights reserved.