测试跨域
This commit is contained in:
parent
75d13febeb
commit
f70a495bb7
@ -3,26 +3,44 @@ package com.example.caseData.core;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.filter.CorsFilter;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig {
|
||||
|
||||
@Bean
|
||||
public WebMvcConfigurer corsConfigurer() {
|
||||
return new WebMvcConfigurer() {
|
||||
@Override
|
||||
public void addCorsMappings(@NonNull CorsRegistry registry) {
|
||||
registry.addMapping("/**") // 允许所有路径
|
||||
.allowedOriginPatterns("*") // 允许所有来源(Spring 2.4+ 用 `allowedOriginPatterns`)
|
||||
.allowedMethods("POST", "GET", "OPTIONS", "PUT", "DELETE", "UPDATE") // 允许的 HTTP 方法
|
||||
.allowedHeaders("Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization") // 允许的请求头
|
||||
.exposedHeaders("Content-Length", "Access-Control-Allow-Origin",
|
||||
"Access-Control-Allow-Headers", "Cache-Control",
|
||||
"Content-Language", "Content-Type") // 允许前端访问的响应头
|
||||
.allowCredentials(false); // 是否允许携带 Cookie
|
||||
}
|
||||
};
|
||||
public CorsFilter corsFilter() {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
|
||||
// 允许所有来源(与 Gin 中的动态 Origin 等价)
|
||||
config.addAllowedOriginPattern("*");
|
||||
|
||||
// 允许的请求方法
|
||||
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "UPDATE"));
|
||||
|
||||
// 允许的请求头
|
||||
config.setAllowedHeaders(Arrays.asList(
|
||||
"Origin", "X-Requested-With", "Content-Type", "Accept", "Authorization"
|
||||
));
|
||||
|
||||
// 暴露哪些响应头给前端
|
||||
config.setExposedHeaders(Arrays.asList(
|
||||
"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers",
|
||||
"Cache-Control", "Content-Language", "Content-Type"
|
||||
));
|
||||
|
||||
// 是否允许携带 Cookie 等认证信息(Gin 里是 false)
|
||||
config.setAllowCredentials(false);
|
||||
|
||||
// 注册跨域配置
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
return new CorsFilter(source);
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user