前端CORS请求接口跨域问题解决方案 (古月)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35061546/article/details/82079999

先配置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");

猜你喜欢

转载自blog.csdn.net/qq_35061546/article/details/82079999