You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Axios调用Spring-Stripe支付接口遇CORS跨域错误求助

Spring + React + Stripe 支付门户CORS错误解决方案

错误信息

Access to XMLHttpRequest at 'http://localhost:8080/api/payment-gateway/charge' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

排查与解决步骤

1. 修复Stripe密钥注入错误

你的PaymentGatewayService中@Value注解写法错误,导致密钥无法正确注入,Stripe初始化失败,请求在处理前就抛出异常,无法返回CORS响应头:

// 错误写法
@Value("$sk_test_*******")
// 正确写法:添加大括号
@Value("${sk_test_*******}")

确保配置文件(如application.properties)中存在对应的密钥配置:

sk_test_*******=你的实际Stripe密钥

2. 完善全局CORS配置

仅配置allowedOrigins不足以覆盖preflight请求的所有要求,需要补充允许的请求方法、headers等:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:3000") // 建议指定具体origin,而非通配符*
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                    .allowedHeaders("*")
                    .allowCredentials(true);
        }
    };
}

注意:如果使用通配符*,allowCredentials(true)会失效,生产环境建议明确指定允许的前端域名。

3. 移除重复的CORS配置

你同时在Controller上添加了@CrossOrigin("*")和全局CORS配置,可能产生冲突,建议保留其中一种即可(推荐全局配置)。

4. 检查Spring Security拦截(若使用)

如果项目中集成了Spring Security,需要额外配置允许preflight请求(OPTIONS方法):

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 允许OPTIONS请求通过
            .anyRequest().authenticated();
    }
}

5. 验证请求是否到达后端

在Controller的charge方法开头添加日志,确认请求是否被后端接收:

@PostMapping("/charge")
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<String> charge(@RequestBody PaymentRequest paymentRequest) throws StripeException{
    System.out.println("Received payment request: " + paymentRequest); // 添加日志
    String chargeId = paymentGatewayService.charge(paymentRequest);
    return chargeId != null ? new ResponseEntity<String>(chargeId, HttpStatus.OK) :
            new ResponseEntity<>("Please check the credit card details",HttpStatus.BAD_REQUEST);
}

如果日志未打印,说明请求被拦截,需要检查拦截器、过滤器等配置。


内容的提问来源于stack exchange,提问作者Rashmika Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 21:12:59