Whenever I go back in history on my Laravel website, the response I see is this:
{}
When I go forward to where I was before that, it shows those braces as well.
The problem doesn't occur if I launch Developer Tools in Chrome with Disable Cache option. The Content-Type of what's returned is indeed application/json. In Firefox there's no such problem.
My new discovery is that it is happening because one of my Middlewares. I wrote AjaxJson middleware to translate all Ajax requests to JSON response. Weirdly, when I go back in history, Google Chrome makes this request Ajax. It contains this header:
X-Requested-With: XMLHttpRequest
And therefore $request->ajax() returns true.
This is my middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Response;
class AjaxJson
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
if (!$request->ajax()) {
return $response;
}
if (!$response instanceof Response) {
return $response;
}
return response()->json($response->getOriginalContent(), $response->status());
}
}
@SaeedPrez For some reason, now it's fine on my local environment, but still occurs on DigitalOcean. It only happens, when the page is being taken from cache. And it used to be on my Homestead before, now it's loaded each time.
@SaeedPrez It's only in Chrome. Do you have an idea how to fix it? I prefer not to accept the fact that some users will be unable to browse back in history :D
It's a whole new full time job keeping up with these browsers, whenever I run into problems like this I try google it, try some stuff, find a solution or workaround and move on.
@bashy You are probably right. For now, I'm using same URLs for a few actions. But they are not those that run when I click back button. Do you have an idea why it behaves so weird? When I go back to ANY page, including home page, Google Chrome behaves like it's Ajax page and adds this X-Requested-With: XMLHttpRequest header.
Solution with no-store is, I hope, temporary. I feel like I do something wrong and those same URLs for Ajax and non-Ajax calls might be the reason. I still don't understand why though.
This cache solution stopped working, I'm now changing all URLs to be separate for Ajax and for non-ajax. I still don't understand this issue though. Why is this header being sent on back?
For experiment, I made a middleware that runs if my site is being loaded with Ajax. I was displaying a warning then. What happened, was that on each back in history, this warning was being shown. It's ridiculous.