为什么 JSON 类型的 HTTP 501 错误以 text/html 而不是 application/json 的形式呈现给 UI?

Why HTTP 501 error of type JSON presented to UI as text/html instead of application/json?

我在 Apache 上有前端 Angular 运行,在 Tomcat 上有后端 Spring REST API。

我想在某些错误情况下抛出 500 错误,并希望该响应显示为 Json 到 UI(内容类型为 application/json)。这在我的本地工作正常,正如预期的那样 Angular 能够解释 Json 响应但是当涉及到一些常见的 QA 环境时它失败了,因为 501 错误呈现给 UI 作为 text/html Angular 无法消化。

我的本地和 QA 之间的区别是,Angular 在节点上是 运行,而 QA 使用 Apache。正在将带有 501 http 代码的 json 响应转换为 html 类型的 apache 吗?

我在浏览器上得到的响应如下。

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>500 Not Implemented</title>
</head><body>
<h1>Internal Server error</h1>
<p>GET to /test/customer/getCustomer not supported.<br />
</p>
</body></html>

最后我找到了导致 Apache 用它自己的错误文档替换所有非 2XX 响应的原因。您需要做的就是注释或触发 ProxyErrorOverride。使用此 Apache 将代理从后端服务器向 UI 传递错误响应而不会丢失内容,例如它发送 Json 类型的错误响应而不会丢失 headers.

ProxyErrorOverride 关闭

希望这对某人有所帮助。