前后端分离解决CORS跨域问题

一、单个Spring Boot应用使用CorsConfig配置类,实现WebMvcConfigurer解决跨域问题

import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路径
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOrigins("*")
                // 是否允许的请求头信息 
                .allowedHeaders(CorsConfiguration.ALL)
                // 是否允许的方法
                .allowedMethods(CorsConfiguration.ALL)
                // 是否允许证书(Cookies),不再默认开启
                .allowCredentials(true)
                // 跨域允许时间
                .maxAge(3600);
    }

}
View Code

二、多模块化Spring Cloud应用使用Gateway网关,配置CorsWebFilter Bean解决跨域问题

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

@Configuration
public class CorsProperties {

    /**
     * 配置跨域
     * @return
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();

        config.setAllowCredentials(Boolean.TRUE);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }


}
View Code

三、在Controller添加上@CrossOrigin跨域注解,此注解只针对当前控制层类或者单个请求方法有效,注解源码中的定义的属性和上述两个差不多

import com.server.entity.Test;
import com.server.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
// or here
public class TestController {

    @Autowired
    private TestService testService;

    @CrossOrigin // is here
    @GetMapping("/test")
    public List<Test> test() {
        return testService.list();
    }

}
View Code
posted @ 2020-09-08 22:04  wessonshin  阅读(277)  评论(0)    收藏  举报