调用Pinata API的pinByHash接口报错:请求格式不符合要求
Pinata API pinByHash接口报错排查
报错核心原因
调用pinByHash接口时,请求数据结构、字段名以及Content-Type设置全部不符合接口要求,具体问题如下:
参数结构与字段名错误:
Pinata的pinByHash接口明确要求请求体格式为{ hashToPin: 'yourHash', pinataMetadata: (optional metadata)},但当前代码存在两个问题:- 哈希字段用了
ipfsPinHash,而非接口要求的hashToPin - 自定义元数据没有包裹在
pinataMetadata字段下,直接平铺在顶级对象中
- 哈希字段用了
请求头Content-Type错误:
pinByHash接口接收JSON格式的请求体,需要设置Content-Type: application/json,但代码错误设置成了multipart/form-data,同时还把JSON对象转成字符串传递,导致接口无法解析请求。
修复后的代码示例
try { // 上传图片到Pinata(此部分代码无问题,保留) const formData = new FormData(); formData.append('file', image); const resFile = await axios({ method: "post", url: "https://api.pinata.cloud/pinning/pinFileToIPFS", data: formData, maxContentLength: 'Infinity', headers: { pinata_api_key: "", // 替换为你的API密钥 pinata_secret_api_key: "", // 替换为你的密钥 "Content-Type": "multipart/form-data", } }); console.log("图片哈希:", resFile.data.IpfsHash); // 修复后的元数据结构与请求配置 const metadata = { hashToPin: resFile.data.IpfsHash, // 修正字段名为hashToPin pinataMetadata: { // 把自定义元数据包裹在pinataMetadata下 name: name, keyvalues: { description: description, price: price, } } }; console.log("修正后的元数据:", metadata); const ImageMetaData = await axios({ method: "post", url: "https://api.pinata.cloud/pinning/pinByHash", data: metadata, // 直接传JSON对象,axios会自动序列化 maxContentLength: 'Infinity', headers: { pinata_api_key: "", // 替换为你的API密钥 pinata_secret_api_key: "", // 替换为你的密钥 "Content-Type": "application/json", // 修正Content-Type } }); console.log("元数据上传响应:", ImageMetaData.data); const result = `https://ipfs.io/ipfs/${resFile.data.IpfsHash}`; // mintThenList(result) } catch (error) { console.log("IPFS上传错误: ", error) }
额外说明
- 不需要手动调用
JSON.stringify()序列化元数据,axios会自动处理JSON格式的请求体 - 确保API密钥和密钥填写正确,这部分虽非本次报错原因,但也是常见问题点
内容的提问来源于stack exchange,提问作者Naincy Chauhan
相关产品推荐
相关产品推荐

