无法在Laravel 5中为特定路线添加CORS

I am using Laravel 5 for my app and to set the content-type I used CORS Middleware which looks like this.

public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With')
            ->header('Content-Type', 'application/json');

    } 

This is the function in Class CORS.

But, when I return a Blade view, for example the auth/login, I get a plain HTML code in the browser instead of getting the actual view of HTML.

When I change the 'Content-Type' to text/html, the views work, but the apis which return and accept json, doesn't work.

Where am I going wrong?

Your issue is that you're telling the bowser you're sending json, but actually sending it HTML.

You can get around this by using the following.

public function handle($request, Closure $next)
{
    $return = $next($request)
        ->header('Access-Control-Allow-Credentials', 'true')
        ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With');

    if ($request->wantsJson())
    {
        $return->header('Content-Type', 'application/json');
    }

    return $return;
}

By using the $request->wantsJson() function you're able to tell if the current request is asking to receive json or not, it does this by checking the accepted content-type header. See: https://github.com/laravel/framework/blob/5.0/src/Illuminate/Http/Request.php#L581