springboot跨域处理

发布于 2021-07-05  893 次阅读


因为以前使用的都是SpringBoot-web作为控制层,但是最近使用的是webFlux作为控制层,跨域处理有些不一样

SPringMVC的跨域类(springboot低版本配置有些不一样,用低版本的可以留言)

package com.example.demo.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Collections;

/**
 * @version 1.0
 * @since 2021/07/05 10:59 下午
 * @author dancun
 */
//@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //1,允许任何来源
        corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
        //2,允许任何请求头
        corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
        //3,允许任何方法
        corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
        //4,允许凭证
        corsConfiguration.setAllowCredentials(true);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }
}

WebFlux的跨域处理为

package com.example.demo.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.config.CorsRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;

/**
 * @author dancun
 */
@Configuration
public class WebFluxCors implements WebFluxConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/**")
                .allowedMethods("POST","PUT","GET","OPTIONS","DELETE","PATCH")
                .allowedHeaders("*")
                .allowedOrigins("Access-Control-Allow-Origin")
                .allowedOriginPatterns("*")
                .maxAge(10000)
                .allowCredentials(true);
    }
}

除了跨域处理不一样外 context-path项目路径设置也不一样

#web的配置为(SpringBoot2.0以后) 
server:
  port: 8081
  servlet:
    context-path: /path

#web的配置为(SpringBoot2.0之前) 
server:
  port: 8081
  context-path: /path

#WebFlux的配置为
spring:
  webflux:
    base-path: "/name"