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



我有一些 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 格式? 在不修改应用程序 Web 端的这种响应的情况下,任何最好的方法都可以做到这一点!

AppExceptionsHandler.php-

包括HttpException

use SymfonyComponentHttpKernelExceptionHttpException;

然后在同一文件中找到render()函数,在那里您可以返回 JSON 响应而不是默认渲染:

public function render($request, Exception $exception)
{
if($exception instanceof NotFoundHttpException){
return response()->json("Invalid endpoint.", 404);
}
return parent::render($request, $exception);
}

请注意,您只添加"if",并且在return parent::行之前执行此操作。

您可以像这样返回 JSON 中的所有异常:

public function render($request, Exception $exception)
{
return response()->json($exception->getMessage(), $exception->getCode);
}

您可以在AppExceptionsHandler.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

发送所有 API 调用的标头很重要,即对于 Vue.js 中的 Laravel 项目,在 'resoures/assets/js/bootstrap 中配置了 Axios.js

window.axios = require('axios');
window.axios.defaults.headers.common={
'X-CSRF-TOKEN': window.Laravel.csrfToken,
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json', // here!
'Authorization': 'Bearer ' + theToken,
};

该 api 将不再回答任何 html。您可以使用邮递员进行测试/开发。

最新更新