开发过程当中老是会据说到跨域这个问题,一直没有详细的了解过,这里我就详细的梳理一下。
源(origin)就是协议、域名和端口号。html
同源策略是浏览器的一个安全功能,不一样源的客户端脚本在没有明确受权的状况下,不能读写对方资源。因此xyz.com下的js脚本采用ajax读取abc.com里面的文件数据是会被拒绝的。前端
同源策略限制了从同一个源加载的文档或脚本如何与来自另外一个源的资源进行交互。这是一个用于隔离潜在恶意文件的重要安全机制。java
URL由协议、域名、端口和路径组成,若是两个URL的协议、域名和端口所有相同,则表示他们同源。不然,只要协议、域名、端口有任何一个不一样,就是跨域。jquery
前端页面使其访问8081端口的接口:git
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>跨域测试-8080端口</title> </head> <body> <button id="test">8080 -> 8081</button> </body> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script> $("#test").click(function () { $.ajax({ url: "http://localhost:8081/hello", type: "post", success:function (res) { alert(res) } }) }); </script> </html>
火狐浏览器进行跨域请求拦截github
建立一个/hello的接口ajax
/** * 跨域8080端口方法 * @author zhouzhaodong */ @RestController public class CrossDomainTwoController { @RequestMapping("/hello") public String hello(){ return "这是一个来自8081端口的接口!"; } }
点击后观察浏览器,因为没有进行任何配置,因此依旧报错spring
/** * 跨域8080端口方法 * @author zhouzhaodong */ @RestController public class CrossDomainTwoController { @CrossOrigin @RequestMapping("/hello") public String hello(){ return "这是一个来自8081端口的接口!"; } }
再次点击按钮,发现正常返回信息。跨域
注释掉@CrossOrigin注释浏览器
/** * 定义全局CORS配置 * @author zhouzhaodong */ @Configuration public class MyConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/*") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH") .maxAge(3600); } }; } }
再次点击按钮,发现正常返回信息。
到此为止啦!
https://github.com/zhouzhaodo...