51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

nginx-跨域

这就是跨域的本质

你不能在www.jd.com的网页中发出www.baidu.com/???的请求,这就是跨域

浏览器是强制禁止的

但是你可以用一种方式来绕过去,先请求www.jd.com/hello 然后他会来到jd的nginx,这个nginx做一个代理请求 http://www.baidu.com/a.jpg他帮你去百度那里拿图片,然后再通过nat返回,返回给www.jd.com/hello的前端http请求,这样前端看起来我还是向www.jd.com发起请求嘛,正常!

这就是跨域的本质和解决的方式

你看看你的项目中哪个地方发出了不属于源网站的请求,你就用一种特殊的方式让他发出源网站的请求路径,在源网站的nginx中做特殊路径匹配做proxy_pass来修正它

https://blog.csdn.net/weixin_36380516/article/details/130960035

proxy_pass 容易碰到 跨域问题,可以添加额外的add_header 头信息来允许跨域请求。以下是一个修改后的示例:

        location / {

                proxy_redirect off;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

                add_header 'Access-Control-Allow-Origin' '*';
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                # 设置预检请求的响应头
                if ($request_method = 'OPTIONS') {
                     add_header 'Access-Control-Max-Age' 1728000;
                     add_header 'Content-Type' 'text/plain charset=UTF-8';
                     add_header 'Content-Length' 0;
                     return 204;
                    }
                    
                proxy_pass http://192.168.0.222:8283/;
        }
赞(3)
未经允许不得转载:工具盒子 » nginx-跨域