クロスオリジン対応をLaravel5で行ったので、まとめます。

クロスオリジンに引っかかると、Chromeブラウザのデベロッパーツールでこういうようなエラーがでる。

Failed to load https://[domain name]]/api/~~~~~~~~: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '~~~~~~~~~~~~~' is therefore not allowed access.

最近セキュリティの兼ね合いで厳しくなってきた模様。 ので、サーバ側で許可をしてあげる設定をする必要がある。

クロスオリジンについてはここがわかりやすかった。 CORS (Cross-Origin Resource Sharing) ってなに?

対策手順

middleware作成

$ php artisan make:middleware Cors

middlewareの編集

$ vi app/Http/Middleware/Cors.php
<?php

namespace App\Http\Middleware;

use Illuminate\Support\Facades\Log;
use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {   
        $response = $next($request);

        $http_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : "";

        Log::debug("http_origin = " . $http_origin);
        if ($http_origin == "https://www.example01.com" ||
            $http_origin == "https://www.example02.com" ||
            $http_origin == "https://www.example03.com"
        ) {
            Log::debug("add header");
            $response
                ->header("Access-Control-Allow-Origin" , $http_origin)
                //->header("Access-Control-Allow-Origin" , '*')
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
            Log::debug($response);
        }

        return $response;
    }
}

これだと、https://www.example01.com, https://www.example02.com, https://www.example03.com を許可する実装になります。

Kernel.phpの編集

$ vim app/Http/Kernel.php

この一行を追加。

    'cors' => \App\Http\Middleware\Cors::class,

これで対策できてるはず。

参考

こちらのサイトを参考にさせていただきました、ありがとうございます。