Apache迁移服务器Nginx,出现跨域问题

clipboard.png

clipboard.png

可能是跨域问题,post请求 服务器变化导致,get接口没问题

阅读 321
评论 2019-06-17 提问
    1 个回答

    有两种方式:
    1代码解决,使用cors

            $cors_hosts = ["http://game.a.com","https://game.b.com"];
            $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
            if(in_array($origin,$cors_hosts)){
                header('Access-Control-Allow-Origin', $origin);
            }
            header('Access-Control-Allow-Methods', ['GET, POST, OPTIONS']);
            header('Access-Control-Allow-Credentials', 'true');
            header('Access-Control-Allow-Headers','DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization');
            if($this->request->method() == 'OPTIONS'){
                header('Access-Control-Max-Age',1728000);
                header('Content-Type','text/plain; charset=utf-8');
                header('Content-Length',0);
                header('HTTP/1.1 204 No Content');
            }

    2nginx配置

    map $http_origin $corsHost {
    default 0;
    "~http://game.a.com" http://game.a.com;
    "~https://game.b.com" https://game.b.com;
    }
    
    location ~ .php$ {
    if ($request_method = 'OPTIONS') {
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Origin $corsHost;
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
    add_header Access-Control-Allow-Credentials true;
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain; charset=utf-8';
    add_header 'Content-Length' 0;
    return 204;
    }
    评论 赞赏 2019-06-17
      撰写回答

      登录后参与交流、获取后续更新提醒