Php 强制json中间件

Php 强制json中间件,php,json,laravel,middleware,Php,Json,Laravel,Middleware,嘿,伙计们,我正在制作一个restful api,我决定制作一个始终将头设置为content-type application/json的中间件,但问题是它从来没有这样做过。。当我在postman中发送请求时,它仍然表示内容类型为text/html,尽管有中间件。。更清楚的是,这里是我的中间件: class EnforceJSON { public function handle($request, Closure $next) { $response = $next($

嘿,伙计们,我正在制作一个restful api,我决定制作一个始终将头设置为content-type application/json的中间件,但问题是它从来没有这样做过。。当我在postman中发送请求时,它仍然表示内容类型为text/html,尽管有中间件。。更清楚的是,这里是我的中间件:

class EnforceJSON
{
    public function handle($request, Closure $next)
    {
    $response = $next($request);

    $response->headers->set('Content-Type', 'application/json');

    return $response;
    }

}
即使在web.php中为路由设置了中间件,我仍然可以在postman中看到这一点

您不需要从
中间件设置
内容类型:applicaton/json
头。如果您发送json响应,Laravel将为您设置它

如果你能使用这个功能

return response()->json($response_data, 200);
编辑:

我猜这就是你要找的

class JsonHeader
{
    public function handle($request, Closure $next)
    {
        $acceptHeader = $request->header('Accept');
        if ($acceptHeader != 'application/json') {
            return response()->json([], 400);
        }

        return $next($request);
    }
}

从这个问题的公认答案中得到的信息

Postman将显示您发送的标题,而不是中间件修改后的标题。中间件在收到请求后对其进行操作

如果要检查中间件是否正常工作,请尝试从接收请求的控制器转储请求头:

return ($request->header());

我已经知道了,但是如果我转到/api/login,除非我在postman:O中专门设置了一个Accept:application/json头,否则它将不起作用。除非我这样设置头,否则它将返回一个404。然后将
Accept:application/json
头设置为请求而不是中间件中的响应。如果我通过controller方法设置它,它会起作用,但这里是只有当我通过request传递$request,而不是表单request LoginRequest时,它才起作用。有什么方法可以让我的登录表单请求生效吗?转到这个链接