Closed. This question needs to be more focused。它当前不接受答案。
想改善这个问题吗?更新问题,使其仅关注editing this post的一个问题。
12个月前关闭。
Improve this question
我有一些正在工作的API,无论何时找不到数据或找不到api,我都会收到以下类型错误:
我如何才能以JSON格式获取同一内容?无需在应用的网络端修改这种响应的任何最佳方法!
然后在同一文件中找到
请注意,您只添加了“if”,并且在
要么
您可以像这样返回JSON中的所有异常:
想改善这个问题吗?更新问题,使其仅关注editing this post的一个问题。
12个月前关闭。
Improve this question
我有一些正在工作的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
中-
包括HttpException
:
use Symfony\Component\HttpKernel\Exception\HttpException;
然后在同一文件中找到
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);
}
关于json - 如何在laravel中为api返回json格式的响应而不是html ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60187578/