nginx 跨域问题解决

nginx 跨域

# 问题:
Access to XMLHttpRequest at 'http://huodong.rr.com/common/tencentIm/getImTalkTencentRecordList?fromAccount=&toAccount=&each=10&endTime=2021-01-26+00%3A00%3A00&startTime=2021-01-26+23%3A59%3A59&page=1&size=10&t=1611644616295&sig=1cb8067419afd82d1bcce8aa5df7f7c6' from origin 'http://test-rrzb.admin.renren.com' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.

分析:
Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.

是 token 不被在 Access-Control-Allow-Headers中允许,在 Access-Control-Allow-Headers 后面添加 token 

#解决
在 huodong.rr.com nginx 配置中修改
               location ^~ /common/tencentIm {
                        add_header 'Access-Control-Allow-Origin' *;
                        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,token';
                      }  


请求options 方法单独处理

        ## 前端跨域限制访问配置
        add_header 'Access-Control-Allow-Methods' 'GET,POST,PUT,DELETE,PATCH,OPTIONS';
        add_header 'Access-Control-Allow-Credentials' 'true'; 
        add_header 'Access-Control-Allow-Origin' "$http_origin";
        add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReToken,X-Requested-With,timestamp,token';
        location ~* /(blacklist|follow|shield|complain|feedback|feed|like|comment)/(v1|v1.0.0)/ {
              if ($request_method = 'OPTIONS') {
                return 200;
                }
                proxy_pass         http://wap_test_mc4_10;
                proxy_set_header   Host             test-rrzbapi.aaaa.com;
                proxy_set_header   X-Real-IP        $remote_addr;
                proxy_set_header  X-Forwarded-For  $proxy_add_x_forwarded_for;
                client_max_body_size       50m;
                client_body_buffer_size    128k;
                client_body_temp_path      /data/client_body_temp;
                proxy_connect_timeout      300;
                proxy_send_timeout         300;
                proxy_read_timeout         300;
                proxy_buffer_size          8k;
                proxy_buffers              8 64k;
                proxy_busy_buffers_size    128k;
                proxy_temp_file_write_size 128k;
                proxy_temp_path            /data/proxy_temp;
        }



注:
增加跨域规则后还是报错跨域问题,需要对请求方法 options 单独处理
              if ($request_method = 'OPTIONS') {
                return 200;
                }
原文地址:https://www.cnblogs.com/lixinliang/p/14335393.html