jsonajaxlaravelmetroniclaravel-datatables

Server does not return JSON


In development, the server returns JSON. But in production it does not return JSON. I found that in production, browser does not send X-Requested-With header.

In development - Note the X-Requested-With header

enter image description here

In production - There is no X-Requested-With header

enter image description here

Question

How can I make sure the browser sends X-Requested-With header always?

Please let me know any direction/ideas to consider...

Notes

What I have found so far

In below requests, the first one does not return JSON. But when I add X-Requested-With header using Requestly, the third request returns JSON.

enter image description here


Solution

  • There's a very good chance that AWS ALB is dropping the X-Requested-With header since it's a non-standard header.

    You can create a middleware that adds the header to the incoming request, for example:

    class EnsureThatXRequestedWithHeaderExists
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
         */
        public function handle(Request $request, Closure $next): Response
        {
            $request->headers->set('X-Requested-With', 'XMLHttpRequest');
    
            return $next($request);
        }
    }
    

    However, since you're seeking a JSON response, I think that a better approach would be to return a JSON response from within your API endpoint. This can be done using the json() method as follows:

    return response->json($data);
    

    This way, you don't need to rely on the X-Requested-With header at all.