?
?
?
1.在代碼端(Spring boot)增加以下跨域代碼
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebFilter(filterName = "CorsFilter ") @Configuration public class CorsFilter implements Filter { @Autowired private Environment env; @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; //允許跨域的域名列表,多個(gè)用逗號(hào)隔開 String alloworigin = env.getProperty("alloworigin"); //是否允許帶cookie內(nèi)容 String allowCredentials = env.getProperty("allowCredentials"); response.setHeader("Access-Control-Allow-Origin",alloworigin); //注意:要把 Access-Control-Allow-Credentials 設(shè)置為 False,否則本地開發(fā)調(diào)試會(huì)發(fā)生跨域 response.setHeader("Access-Control-Allow-Credentials", allowCredentials); response.setHeader("Access-Control-Allow-Methods", "GET, POST, HEAD, OPTION"); response.setHeader("Access-Control-Max-Age", "3600"); //response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie, username, usertoken, lan_ip, net_ip, wxapitoken"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Cache-Control,Pragma,Content-Type,Token, username, usertoken "); response.setHeader("Access-Control-Expose-Headers", "username, usertoken "); String method = request.getMethod(); if (method.equalsIgnoreCase("OPTIONS")) { res.getOutputStream().write("Success".getBytes("utf-8")); } else { chain.doFilter(req, res); } } }
?
2.在Ngnix或Tomcat的配置中不要再設(shè)置?Access-Control-Allow-Origin:*?
? ?tomcat是在 conf/web.xml 文件里配置的,全文搜索 Origin 即可找到,如果有設(shè)置需要屏蔽;
?
本文摘自 :https://www.cnblogs.com/