2017-04-14 22 views
3

我想使用帶有節點和vuejs的web3連接到以太坊奇偶校驗節點。如何讓Web3js在VueJS組件中工作?

  • 我正在使用vue-cli和webpack。
  • 奇偶校驗在本地主機上運行。
  • 當我訪問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頭,但它沒有修復它。控制檯錯誤似乎表明奇偶校驗節點需要設置該頭部選項。

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

您應該在您的後端允許跨域請求。 – wostex

+0

我認爲這就是我的http:{headers:{}}設置應該做的。 –

+1

奇偶校驗文檔說你可以這樣做: '[rpc] cors =「*」 hosts = [「*」]。' – wostex

回答

3

的解決方案是創建一個名爲config.toml奇偶配置文件。

文件地點:

  • 的Windows:%USERPROFILE%\應用程序數據\漫遊\奇偶\復仇\ config.toml
  • 的Linux:〜/。當地/股/ io.parity.ethereum/config.toml
  • 的MacOS:$ HOME /庫/ 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的評論。