springboot中跨域问题的几种解决方式

1. 单个接口跨域配置
对于特定的接口,可以在控制器方法上使用@CrossOrigin注解来开启跨域支持。

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/api/data")
    @CrossOrigin(origins = "http://example.com") // 允许来自example.com的请求
    public String getData() {
        return "Data from the server";
    }
}

2. 整个类跨域配置
如果你想让一个控制器类下的所有方法都支持跨域,可以在类级别使用@CrossOrigin注解。

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;

@CrossOrigin(origins = "http://example.com") // 类级别跨域配置
@RestController
public class MyController {
    // ...你的API方法
}

3. 全局跨域配置
为了全局启用跨域,可以创建一个配置类,实现WebMvcConfigurer接口,并覆盖其addCorsMappings方法。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 匹配所有路径
                .allowedOrigins("*") // 允许所有来源,可根据实际情况指定来源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
                .allowedHeaders("*") // 允许所有请求头
                .allowCredentials(true) // 是否允许携带cookie
                .maxAge(3600); // 预检请求的有效期,单位秒
    }
}

4. 使用CorsFilter Bean
还可以通过注册一个CorsFilter Bean来实现全局跨域配置。

import org.springframework.beans.factory.annotation.Value;
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;

@Configuration
public class CorsConfig {

    @Value("${allowed.origins}")
    private String[] allowedOrigins;

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList(allowedOrigins));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);

        return new CorsFilter(source);
    }
}
  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot项目解决跨域问题有以下几种方式: 1. 使用@CrossOrigin注解 可以在Controller的方法上添加@CrossOrigin注解实现跨域请求。例如: ``` @CrossOrigin(origins = "http://localhost:8080") @GetMapping("/hello") public String hello() { return "Hello World!"; } ``` 2. 使用WebMvcConfigurer配置类 可以通过WebMvcConfigurer配置类来实现跨域请求。例如: ``` @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowCredentials(true) .maxAge(3600); } } ``` 3. 使用Filter过滤器 可以通过Filter过滤器来实现跨域请求。例如: ``` @Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; HttpServletRequest request = (HttpServletRequest) req; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With"); response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } } ``` 注意:以上代码仅供参考,实际使用需要根据具体情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值