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

Angular与Spring后端POST请求异常:GET请求不支持问题排查

问题解决步骤

1. Angular请求未发送的核心原因

Angular的HttpClient.post()返回的是冷Observable,只有调用.subscribe()后才会真正发起HTTP请求。你当前的代码只声明了请求,但没有触发执行,所以POST请求根本没发出去。

修改Angular代码,添加订阅触发请求:

ngOnInit(): void {
    this.http.post<any>('http://localhost:8080/api/answers', { title: 'Angular POST Request Example' })
      .subscribe({
        next: (response) => console.log('请求成功:', response),
        error: (err) => console.error('请求失败:', err)
      });
}

2. Spring后端接收参数的适配问题

你前端发送的是JSON对象{title: "xxx"},但后端用@RequestBody String title接收,Spring会尝试把整个JSON字符串直接解析成String,这会导致JSON解析错误。更规范的处理方式有两种:

方法一:创建DTO类接收请求参数

// 定义请求参数对应的DTO类
public class AnswerRequest {
    private String title;

    // 必须保留无参构造器
    public AnswerRequest() {}

    // getter和setter方法
    public String getTitle() { return title; }
    public void setTitle(String title) { this.title = title; }
}

// 修改Controller方法
@PostMapping(path="/answers", produces = MediaType.APPLICATION_JSON_VALUE)
public String handlePostRequest(@RequestBody AnswerRequest request){
    System.out.println("接收的title:" + request.getTitle());
    return "ok";
}

方法二:用Map直接接收参数

如果不想创建DTO类,也可以用Map直接接收JSON对象:

@PostMapping(path="/answers", produces = MediaType.APPLICATION_JSON_VALUE)
public String handlePostRequest(@RequestBody Map<String, String> request){
    String title = request.get("title");
    System.out.println("接收的title:" + title);
    return "ok";
}

3. GET请求错误的原因

你遇到的Request method 'GET' is not supported错误,是因为直接在浏览器地址栏访问http://localhost:8080/api/answers——浏览器地址栏发起的是GET请求,但你的后端只配置了@PostMapping处理POST请求,所以Spring返回不支持GET的错误。这和你Angular的POST请求无关(因为之前的Angular代码没触发请求发送)。

内容的提问来源于stack exchange,提问作者Benedikt Müller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 00:14:54