Laravel 5 and weird bug: curly braces on back

2019-05-03 05:52发布

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.

1条回答
虎瘦雄心在
2楼-- · 2019-05-03 06:29

Try to process the request after validations:

public function handle($request, Closure $next)
{
    if ($request->ajax()) {
        return response()->json($response->getOriginalContent(), $response->status());
    }

    return $next($request);        
}
查看更多
登录 后发表回答