我正在使用一些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格式的同一内容?无需在应用的网络端修改这种响应的任何最佳方法!
您可以在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