[Ethereum] JSON RPC call from javascript with axios

json-rpcreact

I would like to call a geth method via JSON RPC from within a react component. I tried this but I always get the Error: 405 (Method Not Allowed)

Here is my code:

try {
      const response = await axios.post('http://localhost:8501', {
        jsonrpc: '2.0',
        id: + new Date(),
        method: 'eth_accounts',
        params: {
        },
      }, {
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*'
        },
      })

      console.log(response.data.result.address)
      console.log(response.data.result.publicKey)
      console.log(response.data.result.wif)
      console.log(response.data.result)
    } catch(error) {
      console.error(error)
    }

Do the requests have to be POST or GET?

My geth instance is running with the following arguments:

geth --datadir node1/ --syncmode 'full' --port 30311 --rpc --rpcaddr 'localhost' --rpcport 8501 --rpcapi 'personal,db,eth,net,web3,txpool,miner' --bootnodes 'enode://<enode@<127.0.0.1:30310' --networkid 1515 --gasprice '1' -unlock '0x0' --mine

Thank you very much for your help

Best Answer

Do the requests have to be POST or GET?

They should be POST.

The GET contains no body.

If accessing the RPC from a browser, CORS will need to be enabled with the appropriate domain set. ref

The JSON RPC can also be started from the geth console using the admin.startRPC(addr, port) command.

You should denote --rpccorsdomain "THE CORS DOMAINS GOES HERE".

Pass Access-Control-Allow-Origin from the client doesnt enable CORS on the server.

Related Topic