Nginx 跨域处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012893325/article/details/81068882

浏览器将CORS请求分成两类:简单请求(simple request)和非简单请求(not-so-simple request)。

只要同时满足以下两大条件,就属于简单请求。

(1) 请求方法是以下三种方法之一:

        HEAD GET POST

(2)HTTP的头信息不超出以下几种字段:

    AcceptAccept-LanguageContent-LanguageLast-Event-IDContent-Type:

     只限于三个值application/x-www-form-urlencodedmultipart/form-datatext/plain

  凡是不同时满足上面两个条件,就属于非简单请求。

 浏览器对这两种请求的处理,是不一样的。


本次跨域现象:

nginx处理1:

                add_header Access-Control-Allow-Origin *;
                add_header Access-Control-Allow-Headers *;
                add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

结果:还是报403跨域;

nginx处理2:

           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' '*';
                add_header 'Access-Control-Max-Age' 1728000;
                add_header 'Content-Type' 'text/plain charset=UTF-8';
                add_header 'Content-Length' 0;
                return 204;
             }
             if ($request_method = 'POST') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' '*';
             }
             if ($request_method = 'GET') {
                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' '*';
             }

结果:不在报跨域问题。

猜你喜欢

转载自blog.csdn.net/u012893325/article/details/81068882