前端CORS請求接口跨域問題解決方案 (古月)

先配置Nginx

先舉例 以下是我們常用的nginx站點配置(PHP網站爲例)

server {
    listen 監聽端口;
    server_name 域名部分; 
    set $root_path  目錄部分;
    root $root_path;
    index index.php index.html;
    location / {
        if ($request_method = 'OPTIONS') { 
            add_header Access-Control-Allow-Origin $http_origin;
            add_header Access-Control-Allow-Methods OPTIONS,HEAD,GET,POST,DELETE,PUT,PATCH;
            add_header Access-Control-Allow-Credentials true;
            add_header Access-Control-Max-Age 1728000;
            add_header Access-Control-Allow-Headers authorization,content-type,x-requested-with,Accept,Authorization,Origin,Referer,X-Csrf-Token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type;

            return 200; 
        }
        try_files $uri $uri/ /index.php?$query_string;
    }
    location ~* ^/(css|img|js|flv|swf|download)/(.+)$ {
        root $root_path;
    }

    location ~ \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }

}

其中 以下部分就是針對CORS跨域的解決方法
這裏寫圖片描述

其中的 $http_origin 是nginx的一個變量 這樣設置可以允許所有來源的請求 主要是測試服務器和生產服務器不在一起的情況就不用改配置了 這個變量也可以替換成具體的域名

下面配置PHP部分

在php代碼的入口位置增加如下配置即可

$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
header("Access-Control-Allow-Origin: ".$origin);
header("Access-Control-Allow-Methods: OPTIONS,HEAD,GET,POST,DELETE,PUT,PATCH");
header("Access-Control-Allow-Headers: authorization,content-type,x-requested-with,Accept,Authorization,Origin,Referer,X-Csrf-Token,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Requesst-Header: Content-Type, content-type, X-Client-Header");
header("Access-Control-Max-Age: 1728000");
header("Access-Control-Request-Method: POST, GET, PUT, DELETE, PATCH, OPTIONS");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章