[英]HTTP API to get the image of an nft based on contract and NFT ID?
我尝试了很多不同的想法,但无法找到如何通过 HTTP 请求获取 NFT 的图像。 我试图找到返回令牌 URI 的 HTTP API,但找不到任何东西。 没有令牌 URI,我无法在 ipfs 上找到图像。
如果获取到 NFT 的“tokenUri”并粘贴到浏览器
ipfs://tokenUriHERE
您将看到像这样的 json 格式的 NFT 元数据。
{
"name": "name it",
"image": "ipfs://QmR36VFfo1hH2RAwVs4zVJ5btkopGip5cW7ydY4jUQBrKW",
"description": "description",
"attributes": [
{
"trait_type": "Artist",
"value": "value"
},
] }
如果您获得图像 URL 并将其粘贴到浏览器中,您将看到该图像。
如果您想编写代码来获取数据,只需发送获取请求到ipfs://tokenUriHERE
获取 JSON,检索图像然后获取图像。
或者您可以使用库。 在 javascript, web3.storage
import { Web3Storage } from 'web3.storage'
const token = process.env.API_TOKEN
const client = new Web3Storage({ token })
async function retrieveFiles () {
const cid =
'bafybeidd2gyhagleh47qeg77xqndy2qy3yzn4vkxmk775bg2t5lpuy7pcu'
// You can fetch data using any CID, even from IPFS Nodes or Gateway URLs!
const res = await client.get(cid)
const files = await res.files()
for (const file of files) {
console.log(`${file.cid}: ${file.name} (${file.size} bytes)`)
}
}
retrieveFiles()
如果您正在使用 React 进行构建,那么 spectre.xyz 中有一个很棒的库use-nft
nft 可以帮助抽象出 NFT 元数据的不一致格式,从而为您提供用于显示图像的相关 URL。
你可以安装它:
npm install --save use-nft ethers
在使用它之前,您必须将您的应用程序包装在此处所示的提供程序中,但实际使用起来非常简单。
function Nft() {
const { loading, error, nft } = useNft(
"0xd07dc4262bcdbf85190c01c996b4c06a461d2430", // NFT contract address
"90473" // token ID
)
// nft.loading is true during load.
if (loading) return <>Loading…</>
// nft.error is an Error instance in case of error.
if (error || !nft) return <>Error.</>
// You can now display the NFT metadata.
return (
<section>
<h1>{nft.name}</h1>
<img src={nft.image} alt="" />
<p>{nft.description}</p>
<p>Owner: {nft.owner}</p>
<p>Metadata URL: {nft.metadataUrl}</p>
</section>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.