Simple fetch and display using IPFS - CORS issue

Viewed 2506

I'm attempting to fetch the following image hosted on IPFS, and present it dynamically in a webpage:

https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF

I've got the following:

    <html>
  <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval' https: ;script-src 'unsafe-inline' 'unsafe-eval';">
<head>

<script>

let url = new URL("https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF")
;(async function(){
let a = await fetch(url)
document.getElementById('container').innerHTML = a.data
})()
</script>

<style>
  #container {
    background-color: green;
    width:100%;
  }
</style>
</head>
<body>
<div id='container'>
</div>
</body>
</html>

Firefox/chrome give the following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ipfs.io/ipfs/QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF. (Reason: CORS request did not succeed)

Does the "Same Origin Policy" in this error refer to the settings on the server or in the browser?

N.b. this resource (https://ipfs.github.io/public-gateway-checker/) seems to imply that CORS requests should work on the ipfs.io server.

What is the most simple way to fetch and display an image from a remote IPFS node, solely in the browser?

Edit: I've managed to get something partially working, based on the examples at js.ipfs.io.

I still get CORS errors, but it does pull one chunk of text and display it (the image doesn't work still.

Why does this partially work?

<html>

<head>
<script src="https://unpkg.com/ipfs@0.41.0-rc.2/dist/index.min.js"></script>
<script>

async function main() {
  const container = document.getElementById('container')
  let node;
    node = await Ipfs.create({ repo: 'ipfs-' + Math.random()})
  const stream = node.cat('QmPChd2hVbrJ6bfo3WBcTW4iZnpHm8TEzWkLHmLpXhF68A')
  let data = ''

  for await (const chunk of stream) {
    console.log('chunk',chunk)
    data += chunk.toString()
  }
  document.getElementById('container').innerHTML = data

}
main()
</script>

<style>
  #container {
    background-color: green;
    width:100%;
    width:150px;
  }
</style>
</head>
<body>
<div id='container'>
</div>
</body>
</html>

2 Answers

Does the "Same Origin Policy" in this error refer to the settings on the server or in the browser? yes it does refer to the settings on the server as the headers sent from the server are not set to allow-cross-origin. For your request to work you can use a proxy or make your own one on cloudflare or host it on heroku for a quick solution, add this at the beginning of the url
https://cors-anywhere.herokuapp.com/

Related