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

Angular对接Spring Boot遇CORS 403错误,求解决方案

问题描述

我正尝试将Angular开发的前端应用与Java Spring Boot后端对接,通过API传递数据时,每次发起POST请求都会出现如下错误:

missing header CORS "access-control-origin" status code: 403

以下是发起POST请求的页面代码:

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

name = "";
surname = "";
birthday: number = 0;
email = "";
nickname = "";
password = "";
pasDue!: string;
NameAlready!: string;
passAlready!: string;
constructor() { }

public onSubmit(form: NgForm){
    this.name = form.value.FullName;
    this.surname = form.value.Surname;
    this.birthday = form.value.birthday;
    this.email = form.value.eMail;
    this.nickname = form.value.Nickname;
    this.password = form.value.Password;
    this.pasDue = form.value.passwordDue;
    let nickname = this.nickname;
    let birthday = this.birthday;
    let email = this.email;
    let name = this.name;
    let surname = this.surname;
    let password = this.password;
    const url = `http://localhost:8080/api/v1/user?user_name=${this.nickname}&password=${this.password}&name=${this.name}&surname=${this.surname}&birth=${this.birthday}&e_mail=${this.email}`;
     //console.log("url"+url);
     try{
     fetch(url, {
       method: "POST",
       mode: "cors",,,
       headers :{
         "Content-Type":"application/json",
         "Access-Control-Allow-Origin": "*",

       },
       body: JSON.stringify({ nickname, birthday, email, name, surname, password }),
       }).then((resp)=>{
       resp.json();
       }).then((data)=>{
       console.log(data);
       })}catch(err){
       console.log(err);
    
       }
  }
  public onSubmitNew(form: NgForm){
     this.passAlready = form.value.passswordAlready;
     this.NameAlready = form.value.eMail;
  }
  ngOnInit(): void {
  }

}

我已搭建好数据库与后端,请问问题出在哪里?我听说这是跨域问题,该如何解决?

补充说明

附上处理数据库请求的Spring Boot控制器类代码:

package com.example.demo.User;

import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(path = "api/v1/user")
public class UserController {

    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }


    @GetMapping
    public List<UserOfPopster> getStudents(){
        return userService.getStudents();
    }

    @PostMapping
    public void registerNewUser(@RequestBody UserOfPopster user){
        userService.addNewUser(user);
    }

    @DeleteMapping(path = "{user_id}")
    public void deleteUser(@PathVariable("user_id") Long id){
        userService.deleteUser(id);
    }

    @PutMapping(path = "{user_id}")
    public void putUser(@PathVariable("user_id") Long userId, @RequestParam(required = false) String name, @RequestParam(required = false) String eMail){
        userService.updateUser(userId, name, eMail);
    }

 }

我是否需要在此添加启用CORS的配置?能否提供配置结构示例供参考(无需编写完整函数)?


解决方案

问题根源

这确实是**跨域资源共享(CORS)**问题:浏览器出于安全限制,会拦截前端向不同域名/端口发起的请求,除非后端明确允许该跨域请求。你在前端请求里加的Access-Control-Allow-Origin是无效的——这个响应头应该由后端返回,而不是前端发送。

另外你的前端代码还有两个小问题:

  1. mode: "cors",,,这里多了两个逗号,属于语法错误,会导致请求无法正常发起
  2. POST请求同时传了URL参数和请求体,后端的@RequestBody只会解析请求体,URL参数是多余的,建议去掉

解决步骤

1. 修复前端代码的语法错误和冗余参数

修改fetch部分的代码:

const url = `http://localhost:8080/api/v1/user`; // 去掉URL里的冗余参数
try{
fetch(url, {
  method: "POST",
  mode: "cors", // 去掉多余的逗号
  headers :{
    "Content-Type":"application/json",
    // 删除Access-Control-Allow-Origin,这个是后端返回的响应头
  },
  body: JSON.stringify({ nickname, birthday, email, name, surname, password }),
}).then((resp)=> resp.json()) // 需返回resp.json(),否则下一个then拿不到数据
  .then((data)=> console.log(data))
  .catch(err=> console.log(err));
}catch(err){
console.log(err);
}

2. 在Spring Boot后端配置CORS

你需要在后端添加CORS配置,有三种常用方式可选:

方式一:控制器级注解配置

直接在UserController类上添加@CrossOrigin注解,允许指定前端来源的跨域请求:

@RestController
@RequestMapping(path = "api/v1/user")
@CrossOrigin(origins = "http://localhost:4200") // Angular默认端口是4200,按实际端口调整
public class UserController {
    // 控制器原有代码不变
}
方式二:全局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 config = new CorsConfiguration();
        config.addAllowedOrigin("http://localhost:4200"); // 允许的前端域名
        config.addAllowedMethod("*"); // 允许所有HTTP方法
        config.addAllowedHeader("*"); // 允许所有请求头
        config.setAllowCredentials(true); // 如需携带Cookie等凭证,开启此项

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 对所有接口生效
        return new CorsFilter(source);
    }
}
方式三:配置文件方式(Spring Boot 2.4+支持)

在application.properties中添加配置:

spring.web.cors.allowed-origins=http://localhost:4200
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE
spring.web.cors.allowed-headers=*

验证

配置完成后重启Spring Boot后端,再发起前端请求,即可正常通过CORS校验,不会再出现403错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:17:05