问题背景:
前后端分离,前端选用Vue,后端选用Java,vue编译出的静态页面采用ngix发布,在前端访问后端时出现跨域问题。
解决方法:
跨域的问题解决方法有好多种,这里是通过服务端解决,以下是代码实现。
public class AllowOriginFilter implements Filter { @SuppressWarnings("unused")
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request=(HttpServletRequest)req;
response.setHeader("Access-Control-Allow-Origin", "*"); // 设置允许所有跨域访问
response.setHeader("Access-Control-Allow-Methods", "POST,GET,PUT,OPTIONS,DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,Content-Type,Accept,Authorization,token");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req,res);
} public void init(FilterConfig filterConfig) {} public void destroy() {} }
导致跨域问题的情况:
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 |
两个不同的域名 | 不允许 |