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

clipboard.png

clipboard.png

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

阅读 1.8k
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;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题