JAVA端解决跨域(Spring Boot)

2018-03-22  本文已影响0人  peteLee
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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;

/**
 * 跨域设置
 * @see org.springframework.web.bind.annotation.CrossOrigin
 */
@Configuration
public class CorsConfigure {
  @Value("${server.cors.pattern:/api/**}")
  private String pathPattern;

  @Bean
  public WebMvcConfigurer corsConfigurer() {
    LoggerFactory.getLogger(CorsConfigure.class).info("CORS enabled at `{}`, you can change it with property `server.cors.pattern` in application.yml.", pathPattern);
    return new CorsWebMvcConfigurerAdapter(pathPattern);
  }

  private static class CorsWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
    private final String pathPattern;

    public CorsWebMvcConfigurerAdapter(String pathPattern) {
      this.pathPattern = pathPattern;
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
      registry.addMapping(pathPattern);
    }
  }
}

也可以加API上加注解

@CrossOrigin

上一篇下一篇

猜你喜欢

热点阅读