nignx允许跨域请求配置

一.问题说明:

现在项目基本都是前后端分离架构,这时前端请求后端就涉及到跨域的问题,如果不做允许跨域设置,当请求接口时浏览器控制台一般会输出错误信息:

 Access to XMLHttpRequest at 'http://xxxxxx' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

网络请求中:

strict-origin-when-cross-origin

二.解决方案

一般情况,我们前端用vue等框架,只需要使用nginx给后端服务接口做个代理即可,在nginx中增加配置,下面预检配置按需使用

    server {
        listen 8888;
       # server_name localhost;
        client_max_body_size 20m;

        #charset koi8-r;
        #access_log  logs/host.access.log  main;

        location / {
                root    /usr/local/nginx/html;
                index   index.html index.htm;
        }


        location /ke-cloud/{
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Credentials' true;
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE, PATCH';
            add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
      
            #跨域预检请求的跨域设置,如调用接口同时发起了预检请求则必须配置下面信息
            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' 'Content-Type, Authorization';
                add_header 'Content-Length' 0;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                # 跨域预检请求在客户端缓存有效期:20 days
                add_header 'Access-Control-Max-Age' 1728000; 
                return 204;
            }


            proxy_pass http://localhost:9999/;
            proxy_set_header Host localhost:9999;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_connect_timeout 30;
        }
        
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

如下图,每次发送请求,都同时发起了预检请求,由于预检请求方法是OPTIONS,所以请求头Access-Control-Allow-Methods中必须要又OPTIONS,否则预检失败,或导致跨域失败。

同时需要针对预检请求做下面允许跨域设置,否则预检请求不通过(返回403),正式请求将会直接失败

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值