1. 程式人生 > >laravel CORS 支援多點跨域訪問

laravel CORS 支援多點跨域訪問

php artisan make:middleware Cors
<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
    	// Get the list of valid domains from the .ENV file
	    $validDomains = explode(',', env('VALID_CORS_DOMAINS', ''));
	    $requestingDomin = parse_url($request->server('HTTP_ORIGIN'), PHP_URL_HOST);

    	// Check to see if this domain is in an accepted list of domains
	    if ( in_array($requestingDomin, $validDomains) ) {
	    	// Domain is OK, so add the calling domain to the CORS header
		    return $next($request)
			    ->header('Access-Control-Allow-Origin', $request->server('HTTP_ORIGIN'))
			    ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With')
			    ->header('Access-Control-Allow-Credentials', 'true')
			    ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
	    } else {
		    // Domain is not allowed, so don't send CORS header
		    return $next($request);
	    }
    }
}