前言
跨域是指一个域下的文件想要和另一个域下的资源发生HTTP通信时,浏览器出于安全限制所引发的问题。如果协议、子域名、主域名、端口有任何一个不同,都会出现跨域问题。
举个例子,如果一个网页来自https://www.example.com,那么它只能访问同域下的资源,如https://www.example.com/data.json。但如果它想访问https://api.example.com/data.json或https://www.other.com/data.json,就会因为跨域而被浏览器拦截。
解决
spring 中处理跨域的3种方案
- 在需要配置跨域的接口上 使用 @CrossOrigin注解 当有多个接口时 需要配置多个 过于繁琐 不推荐
@RestController public class TestController { @GetMapping("/hello") @CrossOrigin(origins = "localhost:8080",allowedHeaders = "*",methods = RequestMethod.GET,allowCredentials = "true",maxAge = 3600L) public String hello() { return "hello"