Search code examples
node.jsvuejs2vue-componentparityweb3js

How to get Web3js to work inside a VueJS component?


I want to use web3 with node and vuejs to connect to an Ethereum Parity node.

  • I am using vue-cli with webpack.
  • Parity is running on localhost.
  • When I visit http://localhost:8545 I see which tells me Parity is listening.

enter image description here

I created the following Vue component:

<template>
  <div class="hello">
    <h1>{{ title }}</h1>
    <h2>{{ accounts() }}</h2>
  </div>
</template>

<script>
  import Web3 from 'web3'

  export default {
    name: 'hello',
    http: {
      root: '/root',
      headers: {
        AccessControlAllowOrigin: 'true'
      }
    },
    data () {
      return {
        title: 'web3.js App'
      }
    },
    methods: {
      accounts: function () {
        const ethereumUri = 'http://localhost:8545'   // 8540, 8545, 8180

        let web3 = new Web3(new Web3.providers.HttpProvider(ethereumUri))

        if (!web3.isConnected()) {
          return 'Unable to connect to ethereum node at ' + ethereumUri
        } else {
          let accounts = web3.eth.accounts
          return accounts
        }
      }
    }
  }
</script>

When I run npm run dev I get this:

enter image description here

On the console I see this:

enter image description here

I attempted to add an Access-Control-Allow-Origin header using this configuration code, but it did not fix it. The console error seems to indicate that the Parity node needs to set this header option.

    http: {
      root: '/root',
      headers: {
        AccessControlAllowOrigin: 'true'
      }
    },

Solution

  • The solution was to create a Parity config file named config.toml.

    File Location:

    • Windows: %UserProfile%\AppData\Roaming\Parity\Ethereum\config.toml
    • Linux: ~/.local/share/io.parity.ethereum/config.toml
    • macOS: $HOME/Library/Application Support/io.parity.ethereum/config.toml

    File Contents:

    [parity]
    #  Test Network 
    chain = "ropsten"
    
    [rpc]
    # Allows Cross-Origin Requests from domain '*'. 
    cors = "*"
    # Allow connections only using specified addresses. 
    hosts = ["", "http://localhost:8080"]
    

    Reference:

    Thank you wostex for the comment.