【问题标题】:How to get Web3js to work inside a VueJS component?如何让 Web3js 在 VueJS 组件中工作?
【发布时间】:2017-09-11 02:07:01
【问题描述】:

我想使用 web3 和 node 和 vuejs 连接到 Ethereum Parity 节点。

  • 我正在使用带有 webpack 的 vue-cli。
  • Parity 正在本地主机上运行。
  • 当我访问 http://localhost:8545 时,我发现 Parity 正在监听。

我创建了以下 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 时,我得到了这个:

在控制台上我看到了这个:

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

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

【问题讨论】:

  • 您应该在后端允许跨域请求。
  • 我认为这就是我的 http: { headers: {} } 设置应该做的事情。
  • Parity 文档说你可以这样做:[rpc] cors = "*" hosts = ["*"].

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


【解决方案1】:

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

文件位置:

  • 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 的评论。

【讨论】:

    猜你喜欢
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2021-05-25
    • 2016-12-28
    相关资源
    最近更新 更多