欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多域名跨域请求 (Access-Control-Allow-Origin)

程序员文章站 2022-07-12 22:29:32
...
跨域请求多域名设置,根据不同域名的请求设置不同的Access-Control-Allow-Origin
/**
     * @param $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request,\Closure $next)
    {
        $response = $next($request);
        if (is_object($response)) {
            $refer = $_SERVER['HTTP_REFERER'];//  http://webwm.com/     http://localhost:63342/webWM/index.html
            $pattern = '/(http:\/\/[^\/]*)\/.*/';
            preg_match($pattern, $refer, $match);
            $refer = $match[1] ?? '*';
            if (in_array($refer, explode(',', config('bosc.allow')))) {
                $response->header('Access-Control-Allow-Origin', $refer);
            }
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
            $response->header('Access-Control-Allow-Credentials', 'true');
            $response = $this->jsonUnescaped($response->getContent(),$response);
            Log::info("返回数据: ".$response->getContent());
        }
        return $response;
    }
相关标签: 跨域多域名