温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

详解springboot设置cors跨域请求的两种方式

发布时间:2020-09-11 04:27:38 来源:脚本之家 阅读:784 作者:Awbeci 栏目:编程语言

1、第一种:

public class CorsFilter extends OncePerRequestFilter {

  static final String ORIGIN = "Origin";

  protected void doFilterInternal(
    HttpServletRequest request, 
    HttpServletResponse response, 
    FilterChain filterChain) throws ServletException, IOException {
  
    String origin = request.getHeader(ORIGIN);
  
    response.setHeader("Access-Control-Allow-Origin", "*");//* or origin as u prefer
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "content-type, authorization");
  
    if (request.getMethod().equals("OPTIONS"))
      response.setStatus(HttpServletResponse.SC_OK);
    else 
      filterChain.doFilter(request, response);
  
  }
}
@Bean
public CorsFilter corsFilter() throws Exception {
  return new CorsFilter();
}

http
  .addFilterBefore(corsFilter(), UsernamePasswordAuthenticationFilter.class)
  .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
  .headers()
  .cacheControl();

2、第二种:

@Configuration
public class CorsConfig {
  @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    // 设置你要允许的网站域名,如果全允许则设为 *
    config.addAllowedOrigin("http://localhost:4200");
    // 如果要限制 HEADER 或 METHOD 请自行更改
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    // 这个顺序很重要哦,为避免麻烦请设置在最前
    bean.setOrder(0);
    return bean;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI