Laravel response()->json 在验证错误的情况下在服务器上返回 html 页面

问题描述 投票:0回答:1

我有一个 Laravel 8 API 应用程序。下面是我在控制器中的示例测试方法,它返回状态 422 和无效数据 JSON 响应。

public function testInvalid()
    {
        $arrResponse = [
            'success'    => false,
            'message'    => 'message',
            'data'       => [],
            'errors'     => ['error'],
            'error_code' => 422,
        ];

        return response()->json($arrResponse, 422);
    }

上面应该在邮递员中返回 JSON 响应:

{
    "success": false,
    "message": "message",
    "data": [],
    "errors": [
        "error"
    ],
    "error_code": 422
}

但它只适用于

local
机器。

当我在

server
上运行相同的操作时,它会返回
Unprocessable entity
HTML 页面。

但是如果我将其更新为具有相同响应格式的

200 OK
响应代码。然后它也会从
server
返回 JSON 响应。

        return response()->json($arrResponse, 200);

所有其他有效请求都正常工作并从

server
返回 JSON 响应。

我需要检查 Apache Web 服务器配置吗?

注意:我尝试在邮递员请求中传递

Accept: application/json
Content-Type: application/json
标头。还是一样。

laravel apache validation jsonresponse
1个回答
-1
投票

这是由于您请求的

Accept
标头造成的。

如果未提供,Laravel 默认为

Accept: text/html
并且错误处理将为您提供与您的接受标头匹配的响应。

通过提供

Accept: application/json
与您的请求标头,Laravel 也会以 JSON 形式返回错误响应。

© www.soinside.com 2019 - 2024. All rights reserved.