文章目录
1.什么是跨域
1.1 跨域
协议、域名、端口号,至少一个不相同,就是跨域访问
1.2 同源
协议、域名、端口号,全部一样,就是同源
1.3 举例
对比跨域比较:
https://www.baidu.com/index.html
https://www.baidu.com/more/index.html 不跨域 三要素相同
https://map.baidu.com/ 跨域 域名不同
http://www.baidu.com/index.html 跨域 协议不同
https://www.baidu.com:8081/index.html 跨域 端口号不同
2. 同源策略
2.1 DOM同源策略
禁止对不同源页面DOM 进行操作。这里主要场景是iframe跨域的情况,不同域名的iframe是限制互相访问的。
2.2 XMLHttpRequest同源策略
禁止使用XHR对象向不同源的服务器地址发起HTTP请求。
3. Spring Boot跨域解决
3.1 方式1:在请求上添加 @CrossOrigin 注解
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@CrossOrigin
@RequestMapping("/hello")
public String HelloSpring (){
return "hello cors";
}
}
3.2 方式2:WebMvcConfigurer配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/*")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
.maxAge(3600);
}
};
}
}