Nginx 跨域,swagger請求參數無法進行傳遞

當服務器通過nginx反向代理後,如果沒有進行Nginx跨域的設置,那麼請求頭的信息就無法進行傳遞。例如,swagger經過跨域訪問時,請求參數無法傳遞。

這是由於

1、DOM同源策略:禁止對不同源頁面DOM進行操作

2、XmlHttpRequest同源策略:禁止向不同源的地址發起HTTP請求

那麼如何設置Nginx的跨域呢?

    server {
        listen  30001 ;
        server_name  192.168.1.203;

        location / {
            proxy_pass  http://192.168.1.203:31000;
            if ($request_method = OPTIONS ) {
		     add_header Access-Control-Allow-Origin "$http_origin";
		     add_header Access-Control-Allow-Methods "POST, GET, PUT, OPTIONS, DELETE";
		     add_header Access-Control-Max-Age "3600";
		     add_header Access-Control-Allow-Headers "*";
		     add_header Access-Control-Allow-Credentials "true";
		     add_header Content-Length 0;
		     add_header Content-Type text/plain;
		     return 200;
		 }
		  
		  add_header 'Access-Control-Allow-Origin' '$http_origin';
		  add_header 'Access-Control-Allow-Credentials' 'true';
		  add_header 'Access-Control-Allow-Methods' 'GET,PUT,POST,DELETE,OPTIONS';
		  add_header 'Access-Control-Allow-Headers' 'Content-Type,*';
		  proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                  proxy_set_header        Real-Source-IP  $http_real_source_ip;
        }

             error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

設置後,Nginx就可以進行跨域訪問啦

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章