Server does not return JSON

48 Views Asked by At

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

  • Laravel app with Metronic theme
  • Production Fargate instance is behind a AWS ALB
  • In development I use a container (Here it works/Returns JSON)

What I have found so far

  • This is nothing to do with CORS (Cross Origin Resource Sharing) as this is all same/single origin.
  • If I add X-Requested-With header using Requestly (https://requestly.com/) it returns JSON as expected. (But I can't ask all users to install Requestly)

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

1

There are 1 best solutions below

4
Eyad Bereh On BEST ANSWER

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.