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

JS使用Fetch API设置Content-Type为application/json访问Spring返回415错误如何解决

根因定位
  • 核心错误为Fetch API配置字段拼写错误:Fetch的请求头配置项是复数形式headers,你的代码中写为单数header,导致你设置的Content-Type: application/json规则完全未生效,浏览器默认将JSON请求体的Content-Type标记为text/plain,与Spring接口要求的JSON格式不匹配,因此返回415状态码。
修复代码

将配置项中的header改为headers即可,修改后代码如下:

document.querySelector('#formPet').addEventListener('submit', event => {
    event.preventDefault();
    let email= document.querySelector("#email");
    fetch('http://localhost:8080/petForm/'+email.value+'/pets', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        help: "helpme:("
      })
    })
  });
可选排查项(修改后仍报错可核对)
  • 确认Spring项目已引入jackson-databind依赖,用于处理JSON请求的序列化和反序列化,Spring Boot项目默认自带该依赖无需额外配置。
  • 若存在跨域场景,确认Spring的跨域配置中已放开Content-Type请求头的允许规则,避免自定义请求头被跨域校验拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 01:45:04