Laravel 解决跨域和OPTIONS请求问题

Tony哥
2019-12-19 / 0 评论 / 134 阅读 / 正在检测是否收录...

建立或现用公共中间件中handle方法改为如下代码

public function handle(Request $request, Closure $next)
    {
        /**
         * 用于跨域调用
         */
        if($request->isMethod('OPTIONS')){
            $response = response('',200);

        }else{
            $response = $next($request);
        }

        if($referrer = $request->server('HTTP_REFERER') ?? $request->server('HTTP_ORIGIN')){
            preg_match('/^(http[s]?:\/\/)?([^\/]+)/i', $referrer, $match);
            $response->header('Access-Control-Allow-Origin',"{$match[0]}");
            $response->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE');
            $response->header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cookies, Token,content-type');
            $response->header('Access-Control-Allow-Credentials', 'true');
            $response->header('Cache-Control', 'no-store');
        }

        return $response;
    }
0

评论 (0)

取消