美文网首页
JAVA端解决跨域(Spring Boot)

JAVA端解决跨域(Spring Boot)

作者: peteLee | 来源:发表于2018-03-22 10:41 被阅读0次
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

相关文章

网友评论

      本文标题:JAVA端解决跨域(Spring Boot)

      本文链接:https://www.haomeiwen.com/subject/niohqftx.html