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

Infura IPFS配置报错:GET方法不允许及401未授权问题求助

问题描述
  • 调用Infura IPFS服务时收到错误提示「HTTP method GET not allowed」,同时返回401(未授权)状态码;
  • 已配置Infura的Project ID和密钥,但问题仍未解决。

已知需升级至Infura IPFS v3版本,且需将请求方法从GET改为POST,但不清楚具体配置步骤,附相关代码及两张错误截图(截图展示错误详情),求解决方案。

相关代码
/* create-item.js */

import { useState } from 'react'
import { ethers } from 'ethers'
import { create as ipfsHttpClient } from 'ipfs-http-client'
import { useRouter } from 'next/router'
import Web3Modal from 'web3modal'

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

import {
  nftaddress, nftmarketaddress  
} from '../config'

import NFT from '../artifacts/contracts/NFT.sol/NFT.json'
import Market from '../artifacts/contracts/NFTMarket.sol/NFTMarket.json'

export default function CreateItem () {
  const [fileUrl, setFileUrl] = useState(null)
  const [formInput, updateFormInput] = useState({ price: '', name: '', description: '' })
  const router = useRouter()

  async function onChange(e) {
    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 (e) {
      console.log(e)  
    }
  }
  
  async function createItem() {
    const { name, description, price } = formInput
    if (!name || !description || !price || !fileUrl) return
    const data = JSON.stringify({
      name, description, image: fileUrl
    })

    try {
      const added = await client.add(date)
      const url = 'https://ipfs.infura.io/ipfs/${added.path}'
      /* */
      createSale(url)
    } catch (error) {
      console.log('Error uploading file: ', error)
    }
  }

  async function createSale() {
    const Web3Modal = new Web3Modal()
    const connection = await web3modal.connect()
    const provider = new ethers.providers.Web3Provider(connection)
    const signer = provider.getSigner()

    let contract = new ethers.Contract(nftaddress, NFT.abi, signer)
    let transaction = await contract.createToken(url)
    let tx = await transaction.wait()

    let event = tx.events[0]
    let value = event.args[2]
    let tokenId = value.toNumber()

    const price = ethers.utils.parseUnits(formInput.price, 'ether')

    contract = new ethers.Contract(nftmarketaddress, Market.abi, signer)
    let listingPrice = await contract.getListingPrice()
    listingPrice = listingPrice.toString()

    transaction = await contract.createMarketItem(
      nftaddress, tokenId, price, { value: listingPrice }
    )
    await transaction.wait()
    router.push('/')
  }

  return (
    <div className="flex justify-center">
      <div className="w-1/2 flex flex-col pb-12">
        <input
          placeholder="Asset Name"
          className="mt-8 border rounded p-4"
          onChange={e => updateFormInput({ ...formInput, name: e.target.value })}
        />
        <textarea
          placeholder="Asset Description"
          className="mt-2 border rounded p-4"
          onChange={e => updateFormInput({ ...formInput, description: e.target.value })}
        />
        <input
          placeholder="Asset Price in Matic"
          className="mt-2 border rounded p-4"
          onChange={e => updateFormInput({ ...formInput, price: e.target.value })}
        />
        <input
          type="file"
          name="Asset"
          className='my-4'
          onChange={onChange}
        />
        {
          fileUrl && (
            <img className="rounded mt-4" width="350" src={fileUrl} />
          )
        }
        <button
          onClick={createItem}
          className="font-bold mt-4 bg-pink-500 text-white rounded p-4 shadow-lg"
        >
          Create Digital Asset
        </button>
      </div>
    </div>
  )
}
解决方案

1. 升级Infura IPFS v3并配置认证

Infura IPFS v3强制要求API密钥认证,且上传请求必须使用POST方法。修改IPFS客户端初始化代码,加入你的Project ID和密钥:

// 替换为你的Infura Project ID和API密钥
const projectId = "你的Infura Project ID";
const projectSecret = "你的Infura API密钥";
const auth = 'Basic ' + Buffer.from(projectId + ':' + projectSecret).toString('base64');

const client = ipfsHttpClient({
  host: 'ipfs.infura.io',
  port: 5001,
  protocol: 'https',
  apiPath: '/api/v0',
  headers: {
    authorization: auth,
  },
});

2. 修正代码中的语法错误

原代码存在几处低级错误,直接导致执行失败:

  • 模板字符串使用错误:所有单引号包裹的'https://ipfs.infura.io/ipfs/${added.path}'要改成反引号`https://ipfs.infura.io/ipfs/${added.path}`,否则变量无法解析;
  • 变量名错误:createItem函数里的await client.add(date)应为await client.add(data);
  • 函数参数缺失+重复声明:createSale函数需要接收url参数,且不能重复声明Web3Modal变量。

修正后的关键代码片段:

async function onChange(e) {
  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 (e) {
    console.log(e)  
  }
}

async function createItem() {
  const { name, description, price } = formInput
  if (!name || !description || !price || !fileUrl) return
  const data = JSON.stringify({
    name, description, image: fileUrl
  })

  try {
    const added = await client.add(data)
    const url = `https://ipfs.infura.io/ipfs/${added.path}`
    createSale(url)
  } catch (error) {
    console.log('Error uploading file: ', error)
  }
}

async function createSale(url) {
  const web3modal = new Web3Modal()
  const connection = await web3modal.connect()
  const provider = new ethers.providers.Web3Provider(connection)
  const signer = provider.getSigner()

  let contract = new ethers.Contract(nftaddress, NFT.abi, signer)
  let transaction = await contract.createToken(url)
  let tx = await transaction.wait()

  // 后续代码保持不变
}

3. 确认请求方法自动适配

ipfs-http-client调用client.add()时,会自动使用POST方法上传内容,只要客户端配置正确,无需手动修改请求方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 09:01:22