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

fetch提交表单触发Unexpected token e in JSON at position 0报错求解

报错原因分析

Uncaught (in promise) SyntaxError: Unexpected token e in JSON at position 0报错和preventDefault逻辑无关,触发该报错的位置是代码里.then(res => res.json())这一行:你强制要求将接口返回结果按JSON格式解析,但后端实际返回的内容不是合法JSON结构,开头第一个字符为e,大概率是后端返回了error、exception这类纯文本错误信息,导致JSON解析失败。
具体触发原因通常有三类:

  • 后端https://immo-serkas.herokuapp.com/contact接口处理完POST请求后,返回的响应头Content-Type不是application/json,返回体是纯文本字符串而非约定的JSON结构
  • 接口请求触发服务端异常(比如参数校验不通过、服务内部报错),直接返回了错误文本而非标准JSON格式响应
  • 跨域配置异常,返回了跨域报错的纯文本信息,而非正常接口返回
解决方法

先临时修改解析逻辑打印后端返回的原始内容,定位具体问题后再对应修复,优化后容错代码如下:

contactForm.addEventListener('submit', (e) => {
  e.preventDefault();

  let formData = {
    firstname: firstname.value,
    lastname: lastname.value,
    email: email.value,
    message: message.value
  }

  fetch('https://immo-serkas.herokuapp.com/contact', {
    method: 'POST',
    body: JSON.stringify(formData),
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  })
  .then(async res => {
    // 先校验接口响应状态是否正常
    if (!res.ok) {
      const errorText = await res.text()
      throw new Error(`请求失败,状态码:${res.status},错误内容:${errorText}`)
    }
    // 兼容处理:先获取原始文本再尝试转JSON,避免直接解析报错
    const resText = await res.text()
    try {
      return JSON.parse(resText)
    } catch (err) {
      throw new Error(`返回内容不是合法JSON:${resText}`)
    }
  })
  .then(data => {
    console.log("data : ", data)
    if (data) {
      alert("Email Sent");
      document.querySelector('.contact-form').style.display = 'none'
      document.querySelector('.contact-success').style.display = 'block'
    } else {
      document.querySelector('.contact-form').style.display = 'none'
      document.querySelector('.contact-error').style.display = 'block'
    }
  })
  .catch(err => {
    // 捕获所有异常统一处理
    console.error('请求出错:', err)
    document.querySelector('.contact-form').style.display = 'none'
    document.querySelector('.contact-error').style.display = 'block'
  })
})

后续排查步骤:

  • 运行修改后的代码,查看控制台打印的错误详情,确认后端返回的实际内容
  • 如果是后端返回格式不符合预期,调整后端接口逻辑,统一返回JSON格式的响应
  • 如果是参数校验不通过,对应调整前端提交的参数结构,匹配后端校验规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:36:01