0

Hey guys so i'm making a restful api and i decided to make a middleware that always sets the header as content-type application/json however the problem is that it never does that.. when i send the request in postman it still says the content-type is text/html despite the middleware.. to be clearer here is my middleware :

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

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

    return $response;
    }

}

and even after setting the middleware in web.php for the routes i still get this in postman postman's result

flex_
  • 679
  • 2
  • 8
  • 26

2 Answers2

1

You do not need to set Content-Type: applicaton/json header from a middleware. Laravel will set it for you if you send a json response.

If can use this function

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

EDIT:

My guess is this is what you are looking for

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

        return $next($request);
    }
}

Got it from accepted answer of this question How to set header for all requests in route group

Ragas
  • 3,005
  • 6
  • 25
  • 42
  • i already know that but if i go to my /api/login it won't work unless i specifically set a Accept:application/json header in postman :O. it returns a 404 unless i set that header so.. – flex_ Sep 04 '17 at 11:36
  • Then set `accept: appliation/json` header to request not to response in middleware. – Ragas Sep 04 '17 at 12:33
  • it does work if i do set it through the controller method but here is the thing it only works if i pass in $request with Request not with my form request LoginRequest. is there any way i can make it work with my login form request? – flex_ Sep 04 '17 at 12:37
  • Got to this link – Ragas Sep 04 '17 at 13:16
0

Postman will show the headers that you send, not the headers after your middleware has modified them. The middleware operates on a request after it is received ...

If you want to check your middleware is working, try dumping the request headers from the controller that receives the request:

return ($request->header());
Don't Panic
  • 13,965
  • 5
  • 32
  • 51