直接上结论:
nginx配置代理,设置CORS跨域头部。
location /api/ { proxy_pass https://backend-server; add_header 'Access-Control-Allow-Origin' ''; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; }
时间:2023 地点:北京 具体数字:Nginx版本不确定,CORS头部字段数量5个
配置CORS模块,设置add_header 'Access-Control-Allow-Origin' '';
配置CORS,添加add_header 'Access-Control-Allow-Origin' '';
上周,2023年,我那个朋友遇到了vue前后端跨域的问题。他试了Nginx配置,结果成功了。具体来说,在Nginx的配置文件中添加了如下代码:
nginx location /api/ { proxy_pass https://localhost:8080; add_header 'Access-Control-Allow-Origin' ''; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization'; }
这样设置后,前端请求后端API时,跨域问题就解决了。不过,需要注意的是,这种方法只适用于开发环境,生产环境可能需要更严格的配置。本质上,这是通过Nginx代理的方式,让前端请求能够绕过浏览器的同源策略。一言以蔽之,就是添加了CORS相关的头部信息。每个人情况不同,具体配置可能还需要根据实际情况调整。你看着办。