前后端分离后的跨域问题解决方案流程

跨域问题出现:

当前后端分离后,由于ajax和后端的安全机制,会出现跨域问题;

跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制。

所谓同源是指,ip,端口均相同,只要有一个不同,就是跨域。

localhost和127.0.0.1虽然都指向本机,但也属于跨域。

解决方案历史

1. 后端 servlet 解决

/* 允许跨域的主机地址 */
response.setHeader("Access-Control-Allow-Origin", "*");  
/* 允许跨域的请求方法GET, POST, HEAD 等 */
response.setHeader("Access-Control-Allow-Methods", "*");  
/* 允许跨域的请求头 */
response.setHeader("Access-Control-Allow-Headers", "*");  

2. 升级版本 后端 拦截器doFilter解决

public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        httpResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        // 响应类型允许的方法
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");
        // 响应头设置
        httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header, HaiYi-Access-Token");
        
        if (httpRequest.getMethod().equals("OPTIONS")) {
            System.out.println("Filter 过滤器 执行 了 OPTIONS");
            httpResponse.setStatus(202);
           //.setStatus(HttpStatus.NO_CONTENT);
            return;
        }
        
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        
    }

}

3. 前端服务采用JSONP请求

let url = 'http://localhost:8001/';
$.ajax({
  type: 'get',
  dataType: 'jsonp',
  url: url,
  jsonp: "callback",
  success: function (res) {
    console.log('success',res)
  },
  error (err) {
    console.error(err)
  }
})

4. nginx转发请求:

server {
    listen       8888
    server_name  192.168.0.106;

    #charset koi8-r;
    #access_log  logs/host.access.log  main;

    location / {
	    proxy_pass  http://192.168.0.106:8100;
	    #root   html;
        #index  index.html index.htm;
	}

	location ~ /cq_control/ {
	    proxy_pass  http://192.168.0.106:8080;
	}
}

 

你可能感兴趣的:(javaweb)