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

使用ipfs-http-client向Infura固定文件时返回400 Bad Request求助

问题:使用ipfs-http-client连接Infura时返回400 Bad Request

我使用最新版59.0.0的ipfs-http-client,尝试过多个版本均出现相同问题。已创建Infura项目,获取了Project Id与API密钥,也配置了认证请求头,但调用文件添加接口时,等待一段时间后返回带有红色标记400 Bad Request的Uri哈希。我基于Next.js开发,还尝试过无需认证的旧版本50.1.2,但问题仍未解决,恳请技术帮助。

我使用的相关代码

连接代码

import { create as ipfsClient } from 'ipfs-http-client';

const auth =
    'Basic ' + Buffer.from(PROJECT_ID + ':' + API_KEY_SECRET).toString('base64');

const client = ipfsClient({
    host: "ipfs.infura.io",
    port: 5001,
    protocol: "https",
    headers: {
        authorization: auth,
    },
});

文件固定代码

const file = e.target.files[0];
  
try{
  
    const added = await client.add(
        file,
        {
            progress: (prog) => console.log(`received: ${prog}`)
        }
    )
    const url = `https://ipfs.infura.io/ipfs/${added.path}`;
  
    setFileUrl(url);
}
catch(error){
    console.log(error);
}

旧版本50.1.2尝试代码

const client = ipfsHttpClient("https://ipfs.infura.io:5001/api/v0");

解决方案

  • 验证认证信息准确性:确认PROJECT_ID和API_KEY_SECRET与Infura项目页面的内容完全一致,无空格、拼写错误;检查Buffer转base64时,两者是否用冒号:正确分隔。
  • 调整客户端配置方式:新版ipfs-http-client推荐直接用url参数配置,避免拆分参数导致的拼接错误:
    const client = ipfsClient({
      url: "https://ipfs.infura.io:5001/api/v0",
      headers: {
        authorization: auth,
      },
    });
    
  • 显式设置文件固定参数:Infura要求上传后固定文件,添加pin: true参数确保操作生效:
    const added = await client.add(file, {
      progress: (prog) => console.log(`received: ${prog}`),
      pin: true
    })
    
  • 检查Next.js环境变量配置:若从环境变量读取认证信息,确保.env.local中变量名以NEXT_PUBLIC_开头(客户端组件需此前缀),且配置无遗漏。
  • 配置Next.js CORS规则:开发环境下,在next.config.js添加CORS配置,避免跨域问题:
    module.exports = {
      async headers() {
        return [
          {
            source: '/api/:path*',
            headers: [
              { key: 'Access-Control-Allow-Origin', value: 'https://ipfs.infura.io' },
            ],
          },
        ]
      },
    }
    
  • 用原生Fetch测试API:绕过ipfs-http-client,直接调用Infura API验证是否能正常上传,排除客户端库问题:
    const formData = new FormData();
    formData.append('file', file);
    
    const response = await fetch('https://ipfs.infura.io:5001/api/v0/add?pin=true', {
      method: 'POST',
      headers: {
        authorization: auth,
      },
      body: formData,
    });
    
    const result = await response.json();
    console.log(result);
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:25:19