前端交互篇

前端交互篇 - 跨域


SpringBoot - Cors解决跨域问题 - 本地请求其他域名时cookie无法传输

SpringBoot 利用Cors解决跨域问题

1.依赖
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.WebConfig配置类
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")               // 表示本应用的所有方法都会去处理跨域请求
                .allowedOrigins("*")             // 例如允许:http://localhost:8081请求
                .allowedMethods("*")             // 表示允许通过的请求数
                .allowedHeaders("*")             // 表示允许通过的请求头
                .allowCredentials(true);         // 允许前端传递cookie
    }
}

3.HTML测试代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body onload="testCors()">
	</body>
	<script src="js/jquery-3.2.1.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript">
		function testCors() {
			$.ajax({
   			type:'POST',
   			url:'http://127.0.0.1:10909/apis/test',
   			xhrFields:{withCredentials:true},
   			success:function(result){
				alert(result)
   			},
   		    error: function (err) {
   		    	alert("异常")
   		    }
   		}); 
		}
	</script>
</html>

过滤器- CROS协议

@Component
@WebFilter(filterName = "corsFilter", urlPatterns = "/*")
public class CorsFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest reqs = (HttpServletRequest) servletRequest;

        String origin = reqs.getHeader("Origin");
        if(StringUtils.isEmpty(origin)) {
            origin = reqs.getHeader("Referer");
        }

        response.setHeader("Access-Control-Allow-Origin", origin);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,Authorization,Token");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

// 重点 cookie处设置 根目录 -> nginx,com结尾网站都可用
Cookie cookie = new Cookie("auth_todo_token", MD5Util.MD5(username+password)+MD5Util.MD5(password+username));
cookie.setPath("/");
cookie.setDomain("nginx.com");

// 重点:本地开发host配置 -> 正式上线后项目Domain依据真实后缀修改即可
127.0.0.1    test.nginx.com
47.93.6.66   server.nginx.com

// Html - Ajax请求:
$.ajax({
	type:'POST',
	url:'http://server.nginx.com:10909/apis/loginAccess',
	// 重点:携带跨域cookie
	xhrFields: {
		withCredentials: true
	},
	.....
});

最佳方案 - Nginx解决跨域问题


跨域问题产生原因: 

域名[主域名与子域名也算]不同
端口不同
协议不同
特注:Ip与域名之间网络交互,也属于跨域,如:123.23.23.12 和 www.a.com

因此通过nginx进行反向代理解决该问题

如: nginx部署静态资源 -> 地址为 127.0.0.1/html/index.html

                       接口地址为: 111.111.111.111:8080/apis/test
                       
则可以通过nginx 将127.0.0.1 配置前缀的方式代理真实接口地址即:
127.0.0.1/apis/* ===>  111.111.111.111:8080/apis/test

然后本地界面请求即不会产生跨域问题, 部署详情见nginx篇

升级方案 - oauth2.0


利用oauth2.0 token验证的方式, 网关层代理及nginx代理解决跨域问题和权限验证的问题

原文地址:https://www.cnblogs.com/kkzhilu/p/12859502.html