码上敲享录 > SpringBoot常见问题详解 > springboot实现跨域配置

springboot实现跨域配置

上一章章节目录下一章 2019-05-17已有171人阅读 评论(0)

springboot实现跨域配置


解决方法:

1.配置CorsFilter跨域处理器

import org.springframework.boot.web.servlet.FilterRegistrationBean;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpMethod;

import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import org.springframework.web.filter.CorsFilter;

import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration

public class WebAppConfig implements WebMvcConfigurer {


/**

* 跨域请求

*

* @return

*/

@Bean

public FilterRegistrationBean<CorsFilter> filterRegistrationBean() {

// 对响应头进行CORS授权,值配置了get、head、post、put方法,其它方法你自己加

MyCorsRegistration corsRegistration = new MyCorsRegistration("/**");

corsRegistration.allowedOrigins("*")

.allowedMethods(HttpMethod.GET.name(), HttpMethod.HEAD.name(), HttpMethod.POST.name(),

HttpMethod.PUT.name(), HttpMethod.OPTIONS.name())

.allowedHeaders("Accept", "Origin", "X-Requested-With", "Content-Type", "Last-Modified", "device",

"token")

.exposedHeaders(HttpHeaders.SET_COOKIE).allowCredentials(true).maxAge(3600);


// 注册CORS过滤器

UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();

configurationSource.registerCorsConfiguration("/**", corsRegistration.getCorsConfiguration());

CorsFilter corsFilter = new CorsFilter(configurationSource);

return new FilterRegistrationBean<CorsFilter>(corsFilter);

}

}





2.重写CorsRegistration,配置路径规则

import org.springframework.web.cors.CorsConfiguration;

import org.springframework.web.servlet.config.annotation.CorsRegistration;

public class MyCorsRegistration extends CorsRegistration {

public MyCorsRegistration(String pathPattern) {

super(pathPattern);

}


@Override

public CorsConfiguration getCorsConfiguration() {

return super.getCorsConfiguration();

}


}


0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交