前后端分离跨域问题总结

跨域问题一般是后端处理,前端只需要在请求时追加{ 'withCredentials': true },一般就能解决跨域问题。

后端:添加CorsFilter过滤器,实现Filter接口

/**跨域请求配置*/
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Set-Cookie, Content-Type, x-requested-with");
        //是否支持cookie跨域
        response.setHeader("Access-Control-Allow-Credentials", "true");
        filterChain.doFilter(servletRequest, servletResponse);
}

前端:向后端发送请求时要追加options:{ 'withCredentials': true }即可。

你可能感兴趣的:(前后端分离,跨域,前后端分离,跨域)