后端技术 · Develop

简单的跨域中间件

小编 · 7月19日 · 2020年

新建后置中间件 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 条回应

必须 注册 为本站用户, 登录 后才可以发表评论!