options 請求跨域問題處理

pyTzy發表於2021-01-22

前後分離經常會出現跨域的問題,下面是工作中處理相關問題,總結的兩種處理方法

一,中介軟體方式處理

針對laravel框架來說

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $IlluminateResponse = 'Illuminate\Http\Response';
        $SymfonyResopnse = 'Symfony\Component\HttpFoundation\Response';
        $headers = [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, PATCH, DELETE',
            'Access-Control-Allow-Headers' => 'token, X-Requested-With, Access-Control-Request-Method, Access-Control-Request-Headers, X-Token, Access-Token, Authorization, Origin, Content-Type, Cookie, Accept',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Expose-Headers', 'X-My-Custom-Header, X-Another-Custom-Header, Authorization, authenticated',
        ];

        // $response是`Illuminate\Http\Response`類的一個例項,
        // 而Passport實際上使用的是`Symfony\Component\HttpFoundation\Response`類響應訊息
        if ($response instanceof $IlluminateResponse) {
            foreach ($headers as $key => $value) {
                $response->header($key, $value);
            }
            return $response;
        }

        if ($response instanceof $SymfonyResopnse) {
            foreach ($headers as $key => $value) {
                $response->headers->set($key, $value);duixi
            }
            return $response;
        }
        return $response;
    }

當然,你可以進行更加細節的處理,就是哪些域名能夠進行跨域$request物件可以獲取地址

二,nginx伺服器處理

新增header請求頭資訊,放到location外面

add_header ‘Access-Control-Allow-Credentials’ ‘true’;
add_header ‘Access-Control-Allow-Origin’ $http_origin;
add_header ‘Access-Control-Allow-Methods’ ‘POST, GET, OPTIONS, PUT, PATCH, DELETE’;
add_header ‘Access-Control-Allow-Headers’ ‘ X-Requested-With, Access-Control-Request-Method, Access-Control-Request-Headers, X-Token, Access-Token, Authorization, Origin, Content-Type, Cookie, Accept’;
add_header ‘Access-Control-Expose-Headers’ ‘X-My-Custom-Header, X-Another-Custom-Header, Authorization, authenticated’;

options 請求跨域問題處理


記錄日常,分享,交流。

本作品採用《CC 協議》,轉載必須註明作者和本文連結
希望你是真正的喜歡code

相關文章