后端技术 · Develop

简单的跨域中间件

•̀.̫•́✧ · 7月19日 · 2020年本文857字 · 阅读3分钟382

新建后置中间件 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',
			'https://www.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

HTTP参考文档

0 条回应