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

使用fetch调用nft.storage的/store API接口返回错误如何解决

问题排查步骤
  • 不要手动设置Content-Type请求头:使用fetch传递FormData对象时,浏览器会自动为请求添加multipart/form-data类型的请求头,并且附带自动生成的boundary分隔符。如果你的代码(或全局请求拦截器、代理服务)手动设置了Content-Type,会导致分隔符丢失,服务端无法正常解析请求体,触发content-type相关报错。
  • 校验image字段的有效性:该字段必须传入标准的File或Blob对象,不能传入base64字符串、本地文件路径、网络URL等非二进制类型。同时需要校验文件是否为空、大小是否超出限制、格式是否为平台支持的图片类型(png/jpg/gif/svg等)。如果你的图片源是base64,需要先转换为Blob再包装为File对象再上传,否则会触发invalid-file报错。
  • 校验接口鉴权信息:打印process.env.TEST_API_KEY确认密钥是否正确读取,检查Authorization头的格式是否为Bearer [你的密钥],注意Bearer和密钥之间必须有且仅有一个空格,密钥本身不能包含多余空格或特殊字符。
  • 排查请求篡改问题:检查是否有浏览器插件、前端请求拦截器、反向代理服务修改了你的请求体或请求头,比如将FormData格式的请求体强制转换为JSON格式,导致服务端解析失败。
正确调用示例

基础上传示例(图片为已经获取到的File对象)

let formData  = new FormData();
// 填写NFT metadata字段
formData.append("name", name);
formData.append("description", description);
// image为<input type="file">获取到的File对象,或者手动构造的File/Blob对象
formData.append("image", image);

fetch("https://api.nft.storage/store",{
  method: "POST",
  body: formData,
  headers: {
    'Authorization': 'Bearer ' + process.env.TEST_API_KEY,
  }
}).then(response => {
  // 先判断请求状态是否正常
  if (!response.ok) {
    return response.text().then(text => {throw new Error(`请求失败:${response.status} ${text}`)})
  }
  return response.json()
}).then((json)=>{
  console.log("上传成功", json)
}).catch(err => {
  console.error("上传报错", err)
})

Base64图片转File对象示例

如果你的图片源是base64格式,可以用以下方法先转换为File对象再传入:

function base64ToFile(base64Str, fileName = 'image.png') {
  const arr = base64Str.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while(n--){
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], fileName, {type: mime});
}

// 使用方法
const imageFile = base64ToFile(你的base64字符串, 'nft-image.png');
formData.append("image", imageFile);

内容的提问来源于stack exchange,提问作者Rohit Handique.

相关产品推荐
方舟 Agent Plan

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

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