Friday 14 April 2017

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></h1>
    <h2></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'
      }
    },



via nu everest

No comments:

Post a Comment