问题背景:
前后端分离,前端选用Vue,后端选用Java,vue编译出的静态页面采用ngix发布,在前端访问后端时出现跨域问题。
解决方法:
跨域的问题解决方法有好多种,这里是通过服务端解决,以下是代码实现。
1 public class AllowOriginFilter implements Filter { 2 3 @SuppressWarnings("unused") 4 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 5 6 HttpServletResponse response = (HttpServletResponse) res; 7 HttpServletRequest request=(HttpServletRequest)req; 8 response.setHeader("Access-Control-Allow-Origin", "*"); // 设置允许所有跨域访问 9 response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE"); 10 response.setHeader("Access-Control-Max-Age", "3600"); 11 response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization,token"); 12 response.setHeader("Access-Control-Allow-Credentials", "true"); 13 chain.doFilter(req,res); 14 } 15 16 public void init(FilterConfig filterConfig) {} 17 18 public void destroy() {} 19 20 21 }
导致跨域问题的情况:
URL地址 | 解释说明 | 是否允许通信 |
http://www.a.com/a.js http://www.a.com/b.js |
同一域名 | 允许 |
http://www.a.com/a/a.js http://www.a.com/b/b.js |
同一域名,不同文件夹 | 允许 |
http://www.a.com/a.js http://www.a.com:8080/b.js |
同一域名,不同端口 | 不允许 |
http://www.a.com/a.js https://www.a.com/b.js |
同一域名,不同协议; 一个是http,另一个是https |
不允许 |
http://www.a.com/a.js https://www.10.0.1.100.com/b.js |
一个域名,一个域名对应的IP | 不允许 |
http://www.a.com/a.js https://www.sub.a.com/b.js |
同一主域名,二级域名不同 | 不允许 |
http://www.a.com/a.js http://www.b.com/b.js |
两个不同的域名 | 不允许 |