如何让Web3js在VueJS组件中工作?

时间:2017-04-14 19:18:21

标签: node.js vuejs2 vue-component parity web3js

我想使用带有node和vuejs的web3连接到以太坊奇偶校验节点。

  • 我正在使用vue-cli和webpack。
  • Parity正在localhost上运行。
  • 当我访问http://localhost:8545时,我看到哪个告诉我Parity正在倾听。

enter image description here

我创建了以下Vue组件:

<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>

当我运行npm run dev时,我明白了:

enter image description here

在控制台上我看到了:

enter image description here

我尝试使用此配置代码添加Access-Control-Allow-Origin标头,但它没有修复它。控制台错误似乎表明Parity节点需要设置此标头选项。

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

1 个答案:

答案 0 :(得分:3)

解决方案是创建一个名为config.toml的Parity配置文件。

文件位置:

  • 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

文件内容:

[parity]
#  Test Network 
chain = "ropsten"

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

<强>参考:

感谢wostex的评论。