spring boot 解决跨域问题最优雅的方式

本文深入解析CORS跨域资源共享机制,阐述了跨域的定义及其在HTTP协议中的实现方式,包括关键的HTTP头信息如Access-Control-Allow-Origin等。同时,提供了Spring框架下两种配置CORS策略的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

CORS :Cross-Origin Resource Sharing 跨域资源共享
跨域:只要协议、域名、端口 三者有任何一个不同即为跨域
就像localhost和127.0.0.1 就是两个不同的域名
所以http://localhost:8081/find_by_id?video_id=2
和http://127.0.0.1:8081/find_by_id?video_id=2 就形成跨域
CORS使用一些HTTP头信息——包括请求和返回

Access-Control-Allow-Origin:访问控制允许源,*表示任意域名
response.setHeader("Access-Control-Allow-Origin","https://example.com");

Access-Control-Allow-Credentials:访问控制允许凭据
它的值只有一个就是 true。跨站点带验证信息时,服务器必须要争取设置这个值,服务器才能获取到用户的cookie。

Access-Control-Allow-Headers
提供一个逗号分隔的列表,表示服务器支持的请求数据类型。
假如你使用自定义头部(比如:x-authentication-token 
服务器需要在返回OPTIONS请求时,要把这个值放到这个头部里,否则请求会被阻止)。

Access-Control-Allow-Methods
一个逗号分隔的列表,表明服务器支持的请求类型(比如:GET, POST,PUT,DELETE,HEAD,OPTIONS)

Access-Control-Expose-Headers
这个返回信息里包含了一组头部信息,这些信息表示哪些客户端可以使用。
其他没有在里面的头部信息将会被限制,比较少用

方式一: 


import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 使用spring 方式
 * spring 4.2起,
 * 可以使用spring 自带的CorsFilter和@CrossOrgin注解
 */
@Configuration
public class CorsConfig {
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置你要允许的网站域名,*表示任意域名
        config.addAllowedOrigin("https://ljh.com");
        // 
        config.addAllowedHeader("*");//* 表示任意头部信息
        config.addAllowedMethod("GET, POST,PUT,DELETE,HEAD,OPTIONS");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        // 这个顺序很重要,为避免麻烦请设置在最前
        bean.setOrder(0);
        return bean;
    }
}

方式二:实现WebMvcConfigurer 的addCorsMappings

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
 * spring boot 方式--全局
 * 我认为比较优雅的解决方案
 * 针对对某个Controller类或者方法可使用@CrossOrigin注解
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
        .allowedOrigins("http://ljh.com")
        .allowedMethods("GET,POST,PUT,DELETE,HEAD,OPTIONS")
        .allowedHeaders("*")
        .allowCredentials(false).maxAge(3600);
    }
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值