Vue.js - Axios 访问 Java 后端跨域问题(支持 Cookie)

解决方案

1、前端(Vue)配置

axios.defaults.withCredentials = true

2、后端(Java)配置

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", "*"); // 设置允许所有跨域访问(不支持带Cookie)
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); // 设置允许所有跨域访问(支持带Cookie)
        response.setHeader("Access-Control-Allow-Credentials", "true"); // 配合前端
        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");
        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

两个不同的域名 

不允许 

 

你可能感兴趣的:(#,Vue.js,#,JavaWeb)