location / { #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' '*'; # } proxy_pass http://localhost:8085; proxy_set_header Host $host:2385; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Real-IP $remote_addr; proxy_next_upstream http_502 http_504 error timeout invalid_header; } }
Java 解决方案
String method = request.getMethod(); if ("options".equalsIgnoreCase(method)) { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); response.setHeader("Access-Control-Allow-Headers", "*"); response.setHeader("Access-Control-Max-Age", "1728000"); response.setHeader("Content-Type", "text/plain charset=UTF-8"); response.setHeader("Content-Length", "0"); response.getOutputStream().close(); return true; } else { response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS"); response.setHeader("Access-Control-Allow-Headers", "*"); return false; } }
在项目开发过程中,多个子系统之间的功能交互,前端出现跨域请求解决方案,前端VUE,后端Java(非springMVC架构)经过测试运行,上述两种方案都可以解决当前需求,当然也存在不同点
1.nginx代理的子系统都需要配置nginx.conf,需要运维支持,不够安全
2.Java方案有一个问题是跨域接口必须单独使用,不然会出现非跨域请求设置跨域接口,无法获取有效数据问题,目前还没有找到问题所在。所以跨域接口必须与非跨域接口单独分开,好处安全问题不用担心
以上是个人经历,不够深入,独家之言,难免偏颇,有错误之处,请留言更正
标签:Control,Java,跨域,header,Access,nginx,add,Allow,response From: https://www.cnblogs.com/limumu/p/18232691