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.
It happens 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());
}
}
What am I doing wrong?
UPDATE
I found out about no-store
value for Cache-Control
response header. It prevents Chrome from using cache when clicking back button. I created a middleware to set Cache-Control
like this:
Cache-Control: private, max-age=0, no-cache, no-store
Please let me know guys, if you know better way of solving this problem.
Try to process the request after validations: