John Doe
John Doe

Reputation: 118

JS-IPFS http client via browser fails due to CORS issue

I am doing some research and testing based on the js-ipfs-http-client browser example here

When I try to get a response from IPFS, I receive the following warning from the firefox console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5001/api/v0/add?wrapWithDirectory=true&progress=true&wrap-with-directory=true&stream-channels=true. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I already tried the recommended (dirty) fix where you change your IPFS config from the terminal:

ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin "[\"*\"]"

But not even this seems to work. I started looking into possibly using custom headers as mentioned here

No luck.

I set up IPFS like so: const ipfsClient = require('ipfs-http-client'); var ipfs = ipfsClient('localhost', '5001');

And then once i get some file from the user, I attempt to save it to IPFS like so:

function saveToIpfsWithFilename (file) 
{
    console.log('running save');

    let ipfsId;
    const fileStream = fileReaderPullStream(file);
    const fileDetails = 
    {
      path: file.name,
      content: fileStream
    };

    const options =
    {
      wrapWithDirectory: true,
      progress: (prog) => console.log(`received: ${prog}`)
    };

    ipfs.add(fileDetails, options).then((response) => 
    {
        console.log(response)
        // CID of wrapping directory is returned last
        ipfsId = response[response.length - 1].hash
        console.log(ipfsId)
    }).catch((err) => {
        console.error(err)
      });
}

Upvotes: 4

Views: 2576

Answers (1)

pranjal85
pranjal85

Reputation: 26

I have also faced same issue then I try to run these following commands and that works for me

ipfs config Addresses.Gateway /ip4/0.0.0.0/tcp/8080
ipfs config Addresses.API /ip4/0.0.0.0/tcp/5001
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin "[\"*\"]"
ipfs config --json API.HTTPHeaders.Access-Control-Allow-Credentials "[\"true\"]"

hope this will solve your problem

Upvotes: 1

Related Questions