前端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");

本文参看了 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS 这篇文章的帮助,有关CORS问题可以进一步了解

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值