I have a nextjs typescript project running in the browser that needs to make the following fetch
request:
const tokenURIResponse = await fetch(
"ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json"
)
This call returns a JSON object that looks like:
{
"name": "PUG",
"description": "An adorable PUG pup!",
"image": "https://ipfs.io/ipfs/QmSsYRx3LpDAb1GZQm7zZ1AuHZjfbPkD6J7s9r41xu1mf8?filename=pug.png",
"attributes": [
{
"trait_type": "cuteness",
"value": 100
}
]
}
However, I keep getting the following errors:
Brave:
Unhandled Runtime Error
TypeError: Failed to fetch
Source
components/NFTBox.tsx (85:39) @ _callee$
83 |
84 | // const tokenURIResponse = await fetch(tokenURI as string)
> 85 | const tokenURIResponse = await fetch(
| ^
86 | "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json",
87 | )
Firefox:
Unhandled Runtime Error
TypeError: NetworkError when attempting to fetch resource.
Source
components/NFTBox.tsx (85:39) @ _callee$
84 |
> 85 | const tokenURIResponse = await fetch(
| ^
86 | "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json",
87 | )
And when I look at the request in my debug tools, I see this:
Request URL: ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg4/?filename=0-PUG.json
Referrer Policy: strict-origin-when-cross-origin
Provisional headers are shown
Learn more
Referer: http://localhost:3000/
User-Agent: XXXXXX
How do I fix this? I've seen questions talking about CORS and articles explaining cors but I'm not sure I follow what the suggestions are.
What do I need to do to make an API call to an IPFS node in my project?
EDIT: For those trying to test, you might need the IPFS Companion
Phil's comment is in the right direction: Few browsers support the "ipfs://" scheme natively.
Currently the browsers which support it out of the box are Brave and Opera, each handles it a bit differently however - so test your code.
The safe cross-browser approach at this point is to extract the CID and create a new URL to address that CID through an IPFS HTTP gateway, and fetch() that URL instead.
You can find a list of IPFS HTTP gateways here: