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

Spring Boot+Angular项目POST登录请求触发CORS跨域错误求助

错误原因

你遇到的是跨域预检请求拦截问题,核心原因有2个:

  1. 前端请求头拼写错误 + HttpHeaders用法错误,导致请求格式不符合预期
  2. Spring Security默认拦截OPTIONS类型的预检请求,返回非200状态,触发CORS校验失败。GET请求属于简单请求不需要预检,所以可以正常访问,Postman不会触发浏览器的CORS校验逻辑,所以请求正常。

后端解决方案(优先配置,一劳永逸)

1. 放行OPTIONS预检请求

在你的Spring Security配置类中添加OPTIONS请求放行规则:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        // 其他原有配置不变,添加下面规则
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        // 保留原有鉴权规则
        .anyRequest().authenticated();
}

2. 配置全局CORS规则

新增CORS配置类,放行前端地址的跨域请求:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:4200") // 允许前端地址访问
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

临时测试也可以直接在AuthController类上添加@CrossOrigin(origins = "http://localhost:4200")注解。

前端修正点

1. 修复请求头错误

你代码里的请求头拼写错误,且HttpHeaders是不可变对象,set方法不会修改原实例,需要修正为:

// 先补全依赖导入
import { HttpClient, HttpHeaders } from '@angular/common/http';

login(username: string, password: string): Observable<any> {
    const data = {
        username: username,
        password: password
    };
    // 修正拼写和HttpHeaders用法
    const headers = new HttpHeaders().set('Content-Type', 'application/json'); 

    const url = `${environment.AUTH_ROUTE}`;
    return this.httpClient.post<any>(url, data, { headers: headers })
        .pipe(
            map(response => {
                localStorage.setItem('token', response.token);
                this.isAuthenticatedSubject.next(true);
                return response;
            })
        );
}

2. (可选)Angular代理正确配置

如果要使用代理避免跨域,在项目根目录新建proxy.conf.json:

{
  "/authenticate": {
    "target": "http://localhost:8080",
    "secure": false,
    "changeOrigin": true
  }
}

启动开发服务时使用命令 ng serve --proxy-config proxy.conf.json,同时把environment.AUTH_ROUTE修改为/authenticate/login即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 23:24:03