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

运行node index.js后无法生成带IpfsHash的Pinata IPFS图片链接

问题:模板字符串变量未解析,IPFS链接生成失败

运行node index.js后,输出内容为https://gateway.pinata.cloud/ipfs/${result.IpfsHash},其中的${result.IpfsHash}未被替换为实际的IPFS哈希值,无法生成完整的图片访问链接。

现有代码:

const pinataSDK = require('@pinata/sdk');
require('dotenv').config();
const fs = require('fs');

const pinata = new pinataSDK(process.env.PINATA_API_KEY, process.env.PINATA_API_SERCRET);
const readableStreamForFile = fs.createReadStream('./images/cool-bear-#1.png');

const options = {
    pinataMetadata: {
        name: "Cool Bear #1",
        keyvalues: {
            customKey: 'customValue',
            customKey2: 'customValue2'
        }
    },
    pinataOptions: {
        cidVersion: 0
    }
};

const pinFileToIPFS = () => {
    return pinata.pinFileToIPFS(readableStreamForFile, options).then((result) => {
        return 'https://gateway.pinata.cloud/ipfs/${result.IpfsHash}'

    }).catch((err) => {
        
        console.log(err);
    });
}

const getMetadata = async () => {
    const imageUrl = await pinFileToIPFS()
    console.log(imageUrl)
}

getMetadata()

原因分析:

JavaScript中,只有**反引号()**包裹的字符串是模板字符串,支持${变量}的插值语法。你当前用**单引号(')**包裹链接字符串,导致${result.IpfsHash}`被当作纯文本输出,不会被解析为变量值。

另外代码存在拼写错误:PINATA_API_SERCRET应为PINATA_API_SECRET(缺少字母C),可能导致API调用失败,建议一并修正。

解决方案:

将返回语句中的单引号替换为反引号,修改后的代码片段:

const pinFileToIPFS = () => {
    return pinata.pinFileToIPFS(readableStreamForFile, options).then((result) => {
        // 用反引号替换单引号
        return `https://gateway.pinata.cloud/ipfs/${result.IpfsHash}`
    }).catch((err) => {
        console.log(err);
    });
}

同时修正环境变量名的拼写错误:

const pinata = new pinataSDK(process.env.PINATA_API_KEY, process.env.PINATA_API_SECRET);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 11:27:22