后端接口允许跨域访问

为了在后端接口中允许跨域访问(CORS),你需要在你的Spring Boot项目中配置CORS。以下是几种实现方式:

方法一:使用全局CORS配置

这是在Spring Boot中最常用的方法之一,配置全局的CORS策略:

import org.springframework.context.annotation.Bean;
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 WebConfig implements WebMvcConfigurer {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**") // 允许跨域访问的路径
                        .allowedOrigins("http://example.com") // 允许跨域访问的域名
                        .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 允许的HTTP方法
                        .allowedHeaders("*") // 允许的请求头
                        .allowCredentials(true) // 是否允许发送cookie
                        .maxAge(3600); // 预检请求的缓存时间(单位:秒)
            }
        };
    }
}

方法二:在控制器方法级别配置CORS

如果你只想对特定的控制器或方法启用CORS,可以使用@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 {

    @CrossOrigin(origins = "http://example.com")
    @GetMapping("/my-endpoint")
    public String myEndpoint() {
        return "Hello, world!";
    }
}

方法三:全局过滤器配置CORS

你也可以通过配置过滤器来处理CORS请求:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.CorsFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

@Configuration
public class MyCorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*"); // 允许的域名,*表示允许所有
        config.setAllowCredentials(true);
        config.addAllowedMethod("*"); // 允许的方法
        config.addAllowedHeader("*"); // 允许的请求头

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

        return new CorsFilter(source);
    }
}

关键点

  1. allowedOrigins: 配置允许跨域访问的域名。使用 * 代表允许所有域名。
  2. allowedMethods: 配置允许的 HTTP 方法。
  3. allowedHeaders: 配置允许的请求头。
  4. allowCredentials: 配置是否允许发送 cookies。
  5. maxAge: 配置预检请求的缓存时间。

注意事项

  • 为了安全,生产环境中最好不要使用 * 作为 allowedOrigins,而是明确指定允许跨域访问的域名。
  • 如果需要允许带有凭据的请求(如 cookies),则 allowedOrigins 不能使用 *,必须明确指定具体的域名。

通过上述配置,你可以在Spring Boot项目中启用CORS,允许跨域访问。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值