跨域請求一般用於前後臺分離,前臺和後臺不是同一個項目,所以在前端請求的時候就會報錯,請求不被允許。這就需要配置跨域請求了,由於項目是使用SpringBoot開發,這裡貼出基於Springboot的配置。
第一步:寫一個配置類來封裝跨域請求參數,省略get,Set
@ConfigurationProperties(prefix = "cors")
public class CorsProperties {
private Boolean enabled;
private String mappingPathPattern = "/**";
private String[] allowedOrigins = {"*"};
private String[] allowedMethods;
private String[] allowedHeaders = {"*"};
private String[] exposedHeaders;
private Long maxAge = 1800L;
private Boolean allowCredentials = true;
}
第二步:配置跨域請求規則
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(CorsProperties.class)
@ConditionalOnProperty(prefix = "cors", name = "enabled", havingValue = "true")
public class CorsAutoConfiguration extends WebMvcConfigurerAdapter {
@Autowired
private CorsProperties properties;
@Override
public void addCorsMappings(CorsRegistry registry) {
CorsRegistration corsRegistration = registry.addMapping(properties.getMappingPathPattern());
corsRegistration.allowedOrigins(properties.getAllowedOrigins())
.allowedHeaders(properties.getAllowedHeaders())
.maxAge(properties.getMaxAge())
.allowCredentials(properties.getAllowCredentials());
if (properties.getAllowedMethods() != null) {
corsRegistration.allowedMethods(properties.getAllowedMethods());
}
if (properties.getExposedHeaders() != null) {
corsRegistration.exposedHeaders(properties.getExposedHeaders());
}
}
}
第三步:項目中如何使用呢.在application.properties中進行如下配置:
#跨域請求配置
# 必選。啟用cors,值是一個布爾值
cors.enabled=true
# 必選。它的值要麼是請求時Origin字段的值,要麼是一個*,表示接受任意域名的請求
cors.allow-origin=*
cors.allow-headers=Content-Type, Cache-Control, Pragma, Origin, Cookie, Link, Authorization, *
閱讀更多 程序猿老王 的文章