Spring Boot --- Spring MVC: Cors跨域


跨域产生的原因

浏览器的同源策略

  • 由于浏览器同源策略,凡是发送请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。

JSONP

CORS

跨域资源共享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");
            }
        };
    }
}

猜你喜欢

转载自blog.csdn.net/d292222100/article/details/81905254