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

React使用Fetch实现表单图片上传失败,遇500及JSON解析错误

React表单图片上传500错误排查与修复

核心问题分析

返回500 Internal Server Error且提示Unexpected token '<',说明服务器处理请求时出错,返回了HTML错误页面而非预期的JSON响应。前端代码存在两处关键问题:

1. 错误设置Content-Type头

手动指定'Content-Type': 'multipart/form-data'会导致浏览器无法自动添加表单边界(boundary),服务器无法正确解析FormData数据,进而触发内部错误。

2. 无效的input类型

表单中type="price"、type="category"、type="discountRate"都是不合法的HTML输入类型,浏览器会默认转为text类型,但可能引发数据格式或提交异常。

修复后的代码

export const ValidationSchemaExample = () => {
  let send = event => {
    event.preventDefault();
    const formData = new FormData(event.target);
    
    fetch('http://localhost:5000/api/product/new', {
      method: 'POST', 
      // 移除手动设置的Content-Type,让浏览器自动处理
      body: formData 
    })
    .then((response) => {
      // 先检查响应状态,避免解析非JSON内容
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
    })
    .then((data) => {
      console.log('Success:', data);
      // window.location='/';
    })
    .catch((error) => {
      console.error('Error:', error);
    }); 
  }

  return (
    <div>
      <h1>admin/project </h1>
      <form onSubmit={send} method="post" >
        <input name="name" placeholder='Enter your name' />
        {/* 修正为合法的input类型 */}
        <input name="price" type="number" placeholder='Enter your price' />
        <input name="category" type="text" placeholder='Enter your category' />
        <input name="minimumQuantity" type="number" placeholder='Enter your minimumQuantity' />
        <input name="discountRate" type="number" placeholder='Enter your discountRate' />
        <input name="image" type="file" placeholder='Enter your image' />
        <button type="submit">Submit</button>
      </form>
    </div>
  )
};

额外注意事项

  • 服务器端需配置处理multipart/form-data的中间件(比如Node.js环境使用multer),否则无法接收文件。
  • 新增响应状态检查逻辑,避免因服务器返回非JSON内容导致的解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 08:35:30