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

使用Polymer 2的iron-ajax请求Spring Boot 2后端遇CORS问题求助

嘿,我之前也踩过这个一模一样的坑!Postman能正常请求但浏览器报CORS错,本质原因是浏览器会自动发送OPTIONS预检请求,而Postman不会——你的Spring Boot后端现在没正确处理这个预检请求,也没返回要求的CORS响应头。下面给你几个靠谱的解决方案:

1. 全局CORS配置(推荐,一劳永逸)

创建一个全局配置类,让所有接口都支持CORS:

@Configuration
public class GlobalCorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 匹配所有接口路径
                .allowedOrigins("http://localhost:你的前端端口") // 替换成你Polymer应用实际运行的地址,比如8081
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") // 必须包含OPTIONS,因为预检请求用的是这个方法
                .allowedHeaders("*") // 允许所有请求头(比如Content-Type、Authorization等)
                .allowCredentials(true); // 如果你的请求需要携带Cookie或认证信息,一定要开这个
    }
}

⚠️ 注意:如果要使用allowCredentials(true),allowedOrigins不能写*,必须指定具体的前端域名。

2. 局部配置(针对单个接口/Controller)

如果不想全局生效,也可以给特定的Controller或方法加@CrossOrigin注解:

@RestController
// 给整个Controller加CORS支持
@CrossOrigin(origins = "http://localhost:你的前端端口", 
             allowedHeaders = "*", 
             methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public class LoginController {

    @PostMapping("/login")
    // 或者只给这个方法单独加
    // @CrossOrigin(origins = "http://localhost:你的前端端口")
    public ResponseEntity<?> handleLogin(@RequestBody LoginDto loginInfo) {
        // 你的登录逻辑代码
        return ResponseEntity.ok("登录成功");
    }
}
3. 如果用了Spring Security,额外配置!

要是你的后端集成了Spring Security,光上面的配置还不够——Security会拦截OPTIONS预检请求,得显式放行:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors() // 启用CORS配置
            .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() // 允许所有OPTIONS请求通过
            // 其他Security规则,比如登录接口放行之类的
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated();
    }

    // 这里可以复用之前的CORS配置,或者直接定义CorsConfigurationSource
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Arrays.asList("http://localhost:你的前端端口"));
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        config.setAllowedHeaders(Arrays.asList("*"));
        config.setAllowCredentials(true);
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}
前端iron-ajax的小提醒

如果后端开了allowCredentials(true),前端的iron-ajax要记得设置with-credentials="true":

<iron-ajax
    url="http://localhost:8080/login"
    method="POST"
    content-type="application/json"
    body='{"username":"test","password":"123456"}'
    with-credentials="true"
    on-response="handleLoginResponse"
    on-error="handleLoginError">
</iron-ajax>

按上面的步骤配置后,浏览器的预检请求就能正常通过,CORS错误应该就消失了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:06:00