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

添加@CrossOrigin注解后Spring仍出现CORS错误求助

解决Spring Boot + Angular的CORS错误问题

问题分析

你的Spring应用配置了server.servlet.contextPath=/ueapp,控制器中的@CrossOrigin注解虽指定了http://localhost:4200,但仍出现CORS错误,核心原因大概率是:

  • 前端请求URL未正确包含/ueapp上下文路径
  • @CrossOrigin注解的作用范围或配置细节存在疏漏
  • 全局CORS配置未覆盖上下文路径下的所有端点

解决方案

1. 确认前端请求URL正确性

确保Angular中发送请求的目标URL是http://localhost:8080/ueapp/users和http://localhost:8080/ueapp/createUser,不要漏掉上下文路径直接使用/users或/createUser。

示例Angular请求代码:

// 获取用户列表
this.http.get('http://localhost:8080/ueapp/users').subscribe(response => {
  // 处理响应
});

// 创建用户
this.http.post('http://localhost:8080/ueapp/createUser', userData).subscribe(response => {
  // 处理响应
});

2. 优化@CrossOrigin注解配置

将@CrossOrigin移至控制器类级别,让所有接口方法自动继承跨域配置,避免重复编写:

package com.unlockestate.ueparent.auth;

import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin(origins = "http://localhost:4200") // 类级别配置,所有方法生效
public class UserController {

    private final UserRepository userRepository;

    public UserController(UserRepository employeeRepository) {
        this.userRepository = employeeRepository;
    }

    @GetMapping("/users")
    public Iterable<User> findAllUsers() {
        return this.userRepository.findAll();
    }

    @PostMapping("/createUser")
    public User addOneUser(@RequestBody User user) {
        if (this.userRepository.findByEmail(user.getEmail()) == null) {
            return this.userRepository.save(user);
        }
        return null;
    }
}

3. 全局CORS配置(推荐)

如果需要为整个应用统一配置跨域,创建全局CORS过滤器,确保覆盖所有上下文路径下的端点:

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 {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfig = new CorsConfiguration();
        // 允许携带Cookie(若前端需要传递认证信息)
        corsConfig.setAllowCredentials(true);
        // 指定允许的前端Origin
        corsConfig.addAllowedOrigin("http://localhost:4200");
        // 允许所有请求头
        corsConfig.addAllowedHeader("*");
        // 允许所有HTTP方法(GET/POST/PUT/DELETE等)
        corsConfig.addAllowedMethod("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 匹配所有路径(包含/ueapp下的所有接口)
        source.registerCorsConfiguration("/**", corsConfig);

        return new CorsFilter(source);
    }
}

注意:使用全局配置后,建议移除控制器上的@CrossOrigin注解,避免配置冲突。

4. 排查预检请求问题

若浏览器发送OPTIONS预检请求失败,检查以下两点:

  • 全局配置是否包含OPTIONS方法(上述配置中addAllowedMethod("*")已覆盖)
  • 若使用Spring Security,需确保放行OPTIONS请求,避免被拦截

验证方法

配置完成后重启Spring应用和Angular项目:

  1. 在浏览器开发者工具的网络标签中查看请求响应头,确认是否存在Access-Control-Allow-Origin: http://localhost:4200
  2. 检查控制台是否仍有CORS错误,若无则配置生效

内容的提问来源于stack exchange,提问作者Görkem Demirkol

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:00:07