我试图弄清楚为什么我的ApiException仍然返回一个text / html响应而不是一个json响应,如ApiException render方法所示。它给了我正确的错误信息,但它没有将它呈现为json。
/**
* Get the checklist (depending on type - send from Vue model)
*/
public function fetchChecklist(Request $request)
{
$id = $request->input('projectId');
$type = $request->input('type');
if (empty($id)) {
throw new ApiException('Project was not provided.');
}
if (! $project = RoofingProject::find($id)) {
throw new ApiException('Project not found.');
}
if (empty($type)) {
throw new ApiException('No checklist type was provided.');
}
switch ($request->input('type')) {
case 'permitting':
$items = $project->permittingChecklist;
break;
case 'permit':
$items = $project->permitReqChecklist;
break;
default:
throw new ApiException('Checklist not found.');
break;
}
return [
'status' => 'success',
'message' => '',
'items' => $items
];
}
应用\例外\ ApiException.php
<?php
namespace App\Exceptions;
class ApiException extends \Exception
{
public function render($request)
{
return response()->json(['status' => 'error', 'error' => $this->message]);
}
}
答案 0 :(得分:2)
在您对API的请求中,您可以尝试将以下内容添加到head / curl调用中以指定数据类型:
"Accept: application/json"
laravel应用程序正在查找请求是否需要json。
答案 1 :(得分:2)
将以下标头设置为这样对我来说很有用
"x-requested-with": "XMLHttpRequest"