Laravel 5.6 服务器端异常 return 响应 json 而不是 html

Laravel 5.6 server side exceptions return response in json instead of html

所以,我注意到从上一个版本 5.6 Laravel returns 开始,服务器端异常在处理时以 json 格式而不是 html 格式ajax POST 个请求。对于我从以前版本开发的调试逻辑来说,这是一个真正的问题,因为我指望 laravel return 将呈现的 HTML 错误页面作为 .responseText的响应,所以我可以轻松地在新的 window 中显示全部内容并清楚地看到它(用于调试目的)。现在发生的事情基本上是这样的:

当我已经知道 Laravel 可以为我呈现时,我真的不想不得不自己开始构建 html 外观。问题是我找不到关于该主题的最新文档,也找不到 return 呈现的 html 内容作为响应的正确方法。所以我的问题是,谁能告诉我呈现 html 内容的最佳替代方案是什么?哪种方法是接收我想要的东西的最佳方式,是否还有任何特定的方法?提前致谢!

编辑 这是我的 ajax 请求:

$.ajax({
    method: "POST",
    url: '/updateModel',
    data: dataObject,
    success: success
});

其中 dataObject 实际上只是请求中包含的数据。我在初始 .js 文件中得到的内容如下:

$(function () {
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
            $(document).ajaxStart(function() {
                showGlobalLoader(true); //shows the loader
            })
            .ajaxStop(function() {
                showGlobalLoader(false); //hides the loader
            })
            .ajaxError(ajaxErrorGlobalFunction); //displays the new window - that's the function in question
        });

然后就是ajaxErrorGlobalFunction函数

function ajaxErrorGlobalFunction(xhr, status, error) {
    if (xhr.responseText) {
        //console.log(xhr.responseText);
        openErrorWindow(xhr.responseJSON);
    }
}


function openErrorWindow(json = "")
{
    var w = window.open('', '_blank', 'scrollbars=no,status=no,titlebar=no');
    $(w.document.body).html(json.message + "\n in file " + json.file + "\n on line " + json.line);
    w.resizeTo(1000, 1000);
    w.moveTo(0, 0);
    w.focus();
}

如您所见,我过去只是将 xhr.responseText 呈现为 window 的 html 内容,但现在我不得不通过提取最来自 json 的重要信息。作为对请求的响应,我真的很想恢复 html 的旧内容。提前致谢!

正如您在异常处理程序中看到的那样 (Illuminate/Foundation/Exceptions/Handler.php:185):

return $request->expectsJson()
    ? $this->prepareJsonResponse($request, $e)
    : $this->prepareResponse($request, $e);

如果请求需要 json 作为响应,它会将其转换为 json,否则它将像以前一样呈现。

向您的 Ajax 请求添加一个 dataType 不是 json 并且这应该有效:

$.ajax({
    method: "POST",
    url: '/updateModel',
    data: dataObject,
    dataType: 'html',
    success: success
});

更新

如果您希望始终将异常显示为HTML,您可以更新异常处理程序的渲染函数 (app/Exceptions/Handler.php) 通过复制父级的渲染函数并删除 expectsJson 三元组:

if (method_exists($e, 'render') && $response = $e->render($request)) {
    return Router::toResponse($request, $response);
} elseif ($e instanceof Responsable) {
    return $e->toResponse($request);
}

$e = $this->prepareException($e);

if ($e instanceof HttpResponseException) {
    return $e->getResponse();
} elseif ($e instanceof AuthenticationException) {
    return $this->unauthenticated($request, $e);
} elseif ($e instanceof ValidationException) {
    return $this->convertValidationExceptionToResponse($e, $request);
}

return $this->prepareResponse($request, $e);