springboot跨域解决
package com.xf.config; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletResponse; /** * @author admin 跨域过滤器 */ @WebFilter(urlPatterns = "/*", filterName = "corsFilter") public class CorsFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse rep, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) rep; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Credentials", "true"); // response.setHeader("Access-Control-Allow-Methods", "POST, GET, // OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Methods", "*"); response.setHeader("Access-Control-Max-Age", "3600"); // response.setHeader("Access-Control-Allow-Headers", "*"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization,X-Requested-With,openid,formId"); chain.doFilter(req, response); } @Override public void init(FilterConfig arg0) throws ServletException { } }
NG添加配置:
add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
在控制台测试:
var xhr = new XMLHttpRequest(); xhr.open('POST', 'https://xxxxxxxx); xhr.send(null); xhr.onload = function(e) { var xhr = e.target; console.log(xhr.responseText); }
能打印出结果就是成功了哦!另:option请求建议直接在nginx处理掉。
if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,PATCH,OPTIONS; #支持put和delete请求 return 200; }