Laravel ApiException 返回 HTML 响应而不是 JSON

use*_*216 4 php laravel laravel-5

我试图弄清楚为什么我的 ApiException 仍然返回文本/html 响应而不是 ApiException 渲染方法中表示的 json 响应。它给了我正确的错误消息,但它没有将它呈现为 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
    ];
}
Run Code Online (Sandbox Code Playgroud)

App\Exceptions\ApiException.php

<?php

namespace App\Exceptions;

class ApiException extends \Exception
{
    public function render($request)
    {
        return response()->json(['status' => 'error', 'error' => $this->message]);
    }
}
Run Code Online (Sandbox Code Playgroud)

jer*_*edy 7

在您对 API 的请求中,您可以尝试将以下内容添加到您的 head/curl 调用中以指定数据类型:

"Accept: application/json"
Run Code Online (Sandbox Code Playgroud)

laravel 应用程序正在寻找请求是否需要 json。