JAVA端解决跨域(Spring Boot)

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,948评论 6 342
  • 第一次从指尖上感觉到了心跳,原以为此次与马总的见面总能保持点淡定,但当独自待在较小而无窗的会议室里,思绪乱飞...
    流善上阅读 228评论 0 0
  • 90后横行的年代,00后都开始崛起,80后已然不是主流。已经忘了什么时候说80后是这个时代的希望,现在更大的希望出...
    环环相扣L阅读 279评论 1 1
  • 现在大家谈智能机操作系统,默认就是iOS和安卓。还有一个Windows系统,需要靠用户抗议才能换来某些开发商的开发...
    考拉产品观察阅读 13,320评论 6 18
  • 《辞旧迎新》 放下包袱辞旧岁, 不忘初心迎新年。 天命已知莫畏远, 千山万水只朝前。 白云山人 20171231 ...
    赛德传播阅读 234评论 0 1