【記錄】簡單的跨域中介軟體

cnguu發表於2019-06-20

後置中介軟體 application/http/middleware/CORS.php

<?php

namespace app\http\middleware;

class CORS
{
    public function handle($request, \Closure $next)
    {
        $response = $next($request);
        $origin = $request->server('HTTP_ORIGIN') ?: '';
        $allow_origin = [
            'https://gleehub.com',
        ];
        if (in_array($origin, $allow_origin)) {
            $response->header('Access-Control-Allow-Origin', $origin);
            $response->header('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept, Origin, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With');
            $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
            $response->header('Access-Control-Allow-Credentials', 'true');
        }
        return $response;
    }
}

ThinkPHP >= 5.1

愛護牙齒

相關文章