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

将$.ajax PUT文件上传请求转换为fetch时遇CORS报错问题排查

从jQuery $.ajax转fetch时PUT文件上传出现CORS报错的排查方向

问题背景

原本使用jQuery的$.ajax实现的PUT文件上传请求可正常运行,但改用fetch API后触发CORS报错,报错信息显示目标资源缺少Access-Control-Allow-Origin头。由于原请求正常,推测并非真正的CORS配置问题,可从以下方向排查:


排查步骤

  1. 清理fetch不兼容的jQuery专属配置参数
    fetch API的配置参数和$.ajax并不通用,你直接照搬了jQuery的processData、mimeType、contentType、data这些参数,而fetch中:

    • 不存在processData、mimeType这类jQuery特有配置项
    • 请求数据需要放在body字段,而非data字段
    • 上传FormData时,绝对不要手动设置Content-Type头,浏览器会自动生成包含正确边界的multipart/form-data头

    修正后的fetch代码示例:

    const formDataObj = new FormData();
    formDataObj.append("file", file, 'test.png');
    
    const settings = {
      method: "PUT",
      headers: {
        "Authorization": `Bearer ${token}`
      },
      body: formDataObj // 替换原来的data字段
    }
    
    try {
      const response = await fetch('https://somedomain.com/upload', settings);
      if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);
      const data = await response.json();
    } catch (err) {
      console.error(err);
    }
    
  2. 对比jQuery与fetch的请求头差异
    打开浏览器开发者工具的Network面板,分别触发原$.ajax请求和fetch请求,对比以下内容:

    • 预检请求(OPTIONS)的请求头是否一致,尤其是Authorization头的存在性
    • 正式PUT请求的Content-Type头,确认fetch的头是否包含正确的边界字符串(比如multipart/form-data; boundary=----WebKitFormBoundaryxxxx),而非手动设置的固定值
  3. 检查服务器响应的解析逻辑
    若服务器返回的JSON字符串未正确设置Content-Type: application/json头,fetch的response.json()方法会抛出解析错误,这个错误可能和CORS报错混淆。可以先改用response.text()获取原始响应内容,确认是否为合法JSON,同时查看响应头的Content-Type值:

    const response = await fetch('https://somedomain.com/upload', settings);
    const rawText = await response.text();
    console.log(rawText); // 先查看原始返回内容
    try {
      const data = JSON.parse(rawText);
    } catch (parseErr) {
      console.error('JSON解析错误:', parseErr);
    }
    
  4. 检查fetch的请求凭据配置
    如果原$.ajax请求携带了凭据(比如Cookie),fetch默认不会发送凭据,需要显式设置credentials: 'include',否则服务器可能因为未识别到会话而返回错误,同时未附带CORS头:

    const settings = {
      method: "PUT",
      headers: {
        "Authorization": `Bearer ${token}`
      },
      body: formDataObj,
      credentials: 'include' // 需携带凭据时添加
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:20:32