前后端联调跨域解决方案

public class CrosFilter implements Filter {
				
				 @Autowired
				 private AcmUtil acmUtil;	
				
				@Override
				public void init(FilterConfig filterConfig) throws ServletException {

				}

				@Override
				public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
						throws IOException, ServletException {

					HttpServletResponse res = (HttpServletResponse) response;
					
					String allowedOrigins = acmUtil.getValue("allowedOrigins"); // 这里是动态从配置文件中读取的需要跨域的ip地址
					
					if (StringUtils.isBlank(allowedOrigins)) {
						allowedOrigins = "*";
					}
					
					res.setHeader("Access-Control-Allow-Origin", allowedOrigins);
					res.setHeader("Access-Control-Allow-Headers",
							"Content-Type,Content-Length, Authorization, Accept,X-Requested-With,token");
					res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
					res.setHeader("Access-Control-Allow-Credentials", "true");
					res.setHeader("X-Powered-By", "Jetty");
					
					filterChain.doFilter(request, response);
				}

				@Override
				public void destroy() {

				}

跨域错误信息:Access to XMLHttpRequest at 'http://192.168.0.120/auth/selectOrderCount' from origin 'http://192.168.0.124:8080' has been blocked by CORS policy:
                Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'http://192.168.0.136:8080' that is not equal to the supplied origin.

   1:      跨域看 from origin 'id地址' 和 Access-Control-Allow-Origin 中的ip地址是否一致

    2:    可以使用注解的方式跨域,在需要跨域的controller类上加到@CrossOrigin(未测试过)

    3:     如果前端传递token到后台,后台每次接收的token不一致需要在res.setHeader里面添加token字段即可

    4:    跨域配置ip时需要加上端口号

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值