ccruiの博客

ccruiの博客

宝塔反代后解决跨域问题

155
2023-11-08

Nginx配置文件中加入:

    # 全局 CORS 配置
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token';

或在反向代理配置中加入:

    set $enable_cors 0;
    if ( $enable_cors = 0 )
    {
      #CORS 配置
      add_header 'Access-Control-Allow-Origin' '*';
    	add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
  	  #是否允许cookie传输
      add_header 'Access-Control-Allow-Credentials' 'true';
  	  add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token';
    }
    
    
    #针对浏览器的options预请求直接返回200,否则会被403 forbidden--invalie CORS request
    if ( $request_method = 'OPTIONS' ) { 
      #CORS 配置
      add_header 'Access-Control-Allow-Origin' '*';
    	add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
  	  #是否允许cookie传输
      add_header 'Access-Control-Allow-Credentials' 'true';
    	add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,X-Data-Type,X-Requested-With,X-Data-Type,X-Auth-Token';
    	return 200;
  	}