springboot跨域请求解决header问题

@Configuration
public class CorsConfig {

    private CorsConfiguration bulidConfig(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedMethod("*");
        corsConfiguration.setMaxAge(3600L);
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfiguration = bulidConfig();
        corsConfiguration.addExposedHeader("jti");
        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsFilter(source);
    }
}
在Spring Boot中实现跨域请求可以通过以下几种方式: 1. 使用注解:可以在Controller类或者方法上使用`@CrossOrigin`注解来允许跨域请求。例如: ```java @RestController @CrossOrigin(origins = "http://example.com") public class MyController { // ... } ``` 上述代码表示只允许来自"http://example.com"域的请求进行跨域访问。 2. 配置类:可以创建一个配置类来配置跨域请求。例如: ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://example.com") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*") .allowCredentials(true) .maxAge(3600); } } ``` 上述代码表示允许所有路径的请求来自"http://example.com"域,允许的请求方法包括GET、POST、PUT和DELETE,允许的请求头为任意值,允许携带凭证(如Cookie),并设置最大缓存时间为3600秒。 3. 使用Filter:可以创建一个Filter来处理跨域请求。例如: ```java @Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; httpResponse.setHeader("Access-Control-Allow-Origin", "http://example.com"); httpResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); httpResponse.setHeader("Access-Control-Allow-Headers", "*"); httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); httpResponse.setHeader("Access-Control-Max-Age", "3600"); chain.doFilter(request, response); } } ``` 上述代码通过设置响应头来允许跨域请求
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值