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

尝试发起POST请求时出现Error 405 Method Not Allowed错误求助

解决POST请求出现405 Method Not Allowed错误的方案

1. 修正Java Controller类名拼写错误

你的Controller方法参数final car car违反Java命名规范,类名首字母必须大写,Spring无法正确解析请求体,会导致请求处理失败并触发405错误。修正后代码:

public void addCars(@RequestBody final Car car) {
    this.carRepository.save(car);
}

2. 移除Angular请求中不必要的响应头

ACCESS_CONTROL_ALLOW_ORIGIN和ACCESS_CONTROL_ALLOW_CREDENTIALS是服务器返回给客户端的响应头,客户端无需主动发送。删除这两个无效头,简化请求配置:

readonly httpOptions = {
    headers: new HttpHeaders({
        "Content-Type": "application/json"
    })
};

若无需额外请求头,直接省略httpOptions参数即可,Angular HttpClient会自动处理默认头信息。

3. 验证路径与路由匹配

确认Spring Boot应用端口为8080,请求路径http://localhost:8080/api/car/create-car与Controller的@RequestMapping("/api/car")和@RequestMapping(value = "/create-car", method = POST)完全匹配。若项目配置了server.servlet.context-path,需在请求URL中追加对应上下文路径。

4. 排查拦截器/安全配置拦截POST请求

若使用Spring Security或自定义拦截器,需确保允许/api/car/create-car路径的POST请求。例如Spring Security中添加放行规则:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers(HttpMethod.POST, "/api/car/create-car").permitAll()
        .anyRequest().authenticated();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:55:37