Nginx前端配置跨域问题,麻烦老哥们指点下
发布于 5 年前 作者 dengnan123 5806 次浏览 来自 问答

之前每次都是后端Java老哥,配的CORS跨域,这次一个新项目,我看老哥还没配置跨域,就想着自己先用Nginx配置下 现在遇到一点问题 首先贴一下我的Nginx配置

   server {
        listen       8008;
        server_name  localhost;
        # 根路径指到index.html
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /df-share {
            add_header 'Access-Control-Allow-Origin' *;
            add_header 'Access-Control-Allow-Credentials' 'true';
            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';


            if ($request_method = 'OPTIONS') {
                add_header 'Access-Control-Allow-Origin' *;
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Length' 0; return 200;
                }

              proxy_pass http://139.217.96.70; # 转发地址
         }
        error_page   405 =200 @405;
        location @405{
            add_header Content-Length 0;
            add_header Content-Type text/plain;
            add_header Access-Control-Allow-Headers *;
            add_header Access-Control-Allow-Methods *;
            add_header Access-Control-Allow-Origin *;
            return 200;
        }
  }

前端调用的API地址

http://localhost:8008

现在页面上是没有跨域的显示了,但是每次请求的时候只发送了一个OPTIONS请求,之前正确的情况应该,先一个OPTIONS请求,后面跟一个正确的请求, 下面截图是发送的OPTIONS请求 image.png 我Nginx哪里配错了吗,求老哥们指导下

4 回复

这时候已经正常了。 至于为什么多会多一次请求,看这个: https://zhuanlan.zhihu.com/p/70032617

@zuohuadong 但是少了一个请求,紧跟着这个请求后面,应该再发一个请求的

@zuohuadong 好的 我看下

回到顶部