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就可以进行跨域访问啦

————————————————

原文链接:https://blog.csdn.net/weixin_38319645/java/article/details/88627850