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

Next.js 13使用Cloudinary上传图片遇CORS缺失及502错误如何解决?

解决Next.js 13中Fetch上传Cloudinary的CORS与502错误

问题出在你手动设置了Content-Type: multipart/form-data请求头。当使用FormData作为fetch请求的body时,浏览器会自动生成包含boundary分隔符的正确Content-Type,手动设置该头会丢失这个关键的boundary参数,导致Cloudinary无法解析请求,返回502错误,进而无法正常返回CORS响应头,触发同源策略报错。

Axios会自动处理FormData的Content-Type生成,所以之前用Axios时能正常工作,切换到Fetch后因为手动设置了错误的请求头才出现问题。

修正后的代码

const data = new FormData();
data.append('file', image);
data.append('upload_preset', 'CodeStacksProfileImages');
data.append('cloud_name', 'codestacks');
data.append('folder', 'CodeStacksProfileImages');

// 无需手动包装Promise,fetch本身返回Promise
const uploadImagePromise = fetch('https://api.cloudinary.com/v1_1/codestacks/image/upload', {
    method: 'POST',
    // 移除手动设置的Content-Type,由浏览器自动处理
    body: data,
});

// 示例:处理上传结果
uploadImagePromise
    .then(res => {
        if (!res.ok) throw new Error(`请求失败:${res.status}`);
        return res.json();
    })
    .then(result => {
        const imageUrl = result.secure_url;
        // 在这里使用返回的图片URL
    })
    .catch(err => console.error('上传出错:', err));

关键说明

  • 移除手动设置的Content-Type头,让浏览器自动生成包含boundary的正确请求头
  • 无需手动创建Promise包裹fetch,fetch本身就是异步Promise,直接使用即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 18:22:37