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

Spring POST请求出现No 'Access-Control-Allow-Origin' header错误求助

解决Spring + Angular POST请求的CORS与415错误

让我们一步步拆解并解决你的问题:

首先看你报错里的两个关键点:

加载http://localhost:8080/statuts失败:
“No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 415.”

这两个错误是关联的:415(不支持的媒体类型)是根源,而CORS错误是因为服务端返回415时没有携带跨域允许的响应头,浏览器才同时抛出了CORS提示。Postman能正常请求是因为它不受浏览器的CORS规则限制,而且默认会设置正确的请求头。

1. 修复Angular请求代码的两个问题

你的Angular POST请求有两处明显问题:

  • 请求URL缺少http://前缀,浏览器会把它当成相对路径发送,导致请求地址错误
  • 手动调用JSON.stringify(exemple)却没有设置Content-Type: application/json请求头,而你的Spring接口明确要求接收JSON格式的请求体(consumes = MediaType.APPLICATION_JSON_VALUE)

修改后的Angular代码可以是这样:

create(exemple: Exemple){
  // HttpClient会自动序列化对象并设置Content-Type为application/json
  return this.http.post("http://localhost:8080/exemples", exemple);
}

如果需要显式指定请求头,也可以这么写:

import { HttpHeaders } from '@angular/common/http';

create(exemple: Exemple){
  const headers = new HttpHeaders({ 'Content-Type': 'application/json' });
  return this.http.post("http://localhost:8080/exemples", exemple, { headers });
}

2. 简化Spring Controller的请求体接收方式

你的Spring代码手动通过request.getReader()读取并反序列化请求体,这种方式容易出错,而且Spring提供了更简洁规范的@RequestBody注解来自动处理JSON反序列化:

@CrossOrigin(origins = "http://localhost:4200")
public class ExempleController {

    @PostMapping(path="", consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody Exemple addExemple(@RequestBody Exemple exemple) {
        // 确保你的Exemple类有正确的getter/setter,或者用Lombok的@Data注解
        statutRepository.save(exemple);
        return exemple;
    }
}

这样Spring会自动将请求的JSON体转换成Exemple对象,无需手动处理流读取和反序列化。

3. (可选)全局CORS配置的正确姿势

如果你想用全局配置替代Controller上的@CrossOrigin,可以创建一个Web配置类,注意要允许OPTIONS预检请求(浏览器跨域POST会先发OPTIONS请求):

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebCorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:4200")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

为什么之前GET/PUT正常?

因为GET请求通常没有请求体,或者PUT请求你可能在Angular里正确设置了请求头,所以服务端能正常处理并返回带有CORS头的响应,浏览器就不会报错。而POST请求因为Content-Type不对导致415,服务端的错误响应没带上CORS头,所以浏览器同时提示了跨域问题。

按照上面的步骤修改后,你的POST请求应该就能正常工作了。

内容的提问来源于stack exchange,提问作者Loïc Thierry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:02:16