Skip to content
Advertisement

How to configure to handle CORS errors in web3 connecting to ganache

I have a react project I am running at http:\localhost:3000 which connects to ganache running at http:\localhost:7545.

I deploy a small smart contract onto ganache which increments a counter and emits an event, like this…

JavaScript

I want to listen to the Pinged and Ponged events from my contract.

As this is just a helper project for something else I am working on I embed the private key from a ganache account and make an account from it…

JavaScript

Then elsewhere in my code I create an instance of my Pong contract called ponger and store it on a context object in my react app, and invoke the ping() contract method using send like this…

JavaScript

This works like a charm and the local callback sent gets invoked correctly.

I add event listeners to my ponger instance…

JavaScript

This is where the fun starts. The message I receive back in ev_Ping is…

JavaScript

So, duh, I need to use websockets instead of HTTP, right? That means I just connect to ws:\localhost:7545 instead of http:\localhost:7545.

(Aside: I do not have any of these issues if I use MetaMask to deliver me web3…)

However I then get a CORS error like this…

JavaScript

So my question is how do I overcome the CORS error? I am not sure if this is a ganache question or an old fashioned CORS question, or what.

I don’t want to give up on event listening and having to parse through event logs just yet – although I realise there probably is a long route to a different solution.

Advertisement

Answer

I figured out what was wrong and it was my fault. The web3 websocket provider does not enforce CORS so it can be used in my use case.

The issue I was having was that even though I change the protocol in the URI I sent web3, I was still asking for an HTTPProvider instead of a WebsocketProvider.

I made a few changes to getWeb3.js for my purposes like this…

JavaScript

This worked fine.

On the plus side it made me understand CORS a lot better. I really don’t like disabling anything in the browser.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement