跨域产生的原因
- 由于浏览器同源策略,凡是发送请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。
JSONP
CORS
CORS
是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing)CORS有两种请求,简单请求和非简单请求。
Spring Boot
中使用Cors
Spring Boot项目中,只需简单配置就能支持跨域请求:
只要在任意@Configuration
类中添加Bean
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;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* 配置ajax跨域访问
*/
@Configuration
public class CorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry
.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "DELETE");
}
};
}
}