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);
	    }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章