spring boot 跨域问题
程序员文章站
2022-03-10 13:11:48
...
这里采用编写Filter过滤器解决。
/**
* 跨域
* @author 向振华
* @date 2018/11/29 14:04
*/
@Component
public class CorsFilter implements Filter {
@Value("${spring.profiles.active}")
private String active;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
Set allowedOrigins= new HashSet();
if (Constants.PROD.equals(active)){
//生产环境
allowedOrigins.add("http://xzh.xzh.com");
allowedOrigins.add("http://47.98.86.111");
}else{
//其他环境
allowedOrigins.add("http://test.xzh.com");
allowedOrigins.add("http://localhost:4865");
}
String originHeader = ((HttpServletRequest) request).getHeader("Origin");
if (allowedOrigins.contains(originHeader)){
httpServletResponse.setHeader("Access-Control-Allow-Origin", originHeader);
httpServletResponse.setHeader("Access-Control-Allow-Headers", "User-Agent,Origin,Cache-Control,Content-type,Date,Server,withCredentials,AccessToken");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
httpServletResponse.setHeader("Access-Control-Max-Age", "1209600");
httpServletResponse.setHeader("Access-Control-Expose-Headers", "accesstoken");
httpServletResponse.setHeader("Access-Control-Request-Headers", "accesstoken");
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
上一篇: HttpServlet相关
下一篇: php实现记事本案例