我尝试使用nginx作为反向代理为服务器上的私有geth节点设置HTTP身份验证。我遵循了以下说明:https://ethereum.stackexchange.com/questions/30357/restricted-access-authentication-for-a-remote-geth-node
我使用curl
测试了我的设置,目前为止一切正常:
curl
-X POST
--header "Content-Type: application/json"
--data '{"jsonrpc":"2.0","method":"eth_accounts","params":[],"id":1}'
https://<user>:<pw>@<domain>
结果:{"jsonrpc":"2.0","id":1,"result":[<addresses>]}
在浏览器中打开域也很好,我看到身份验证提示,输入凭据后没有错误。
我的节点如下:
docker run -d ethereum/client-go:stable
--datadir "/root"
--port 30001
--nat "any"
--nodiscover
--rpc
--rpcaddr "0.0.0.0"
--rpcport 8545
--rpcapi "eth,net,web3,rpc"
--rpccorsdomain "*"
--rpcvhosts "*"
问题
不幸的是,我无法使用web3
连接到我的节点:
web3 = new Web3(new Web3.providers.HttpProvider("https://<user>:<pw>@<domain>"));
console.log(web3.eth.coinbase);
浏览器中的结果:
Error: CONNECTION ERROR: Couldn't connect to node https://<user>:<pw>@<domain>.
// this error I just get in Chrome, not in Firefox. But if I ask with `curl -I` I can see `Access-Control-Allow-Origin` is set.
web3.min.js:1 Access to XMLHttpRequest at 'https://<user>:<pw>@<domain>' from origin 'https://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
答案 0 :(得分:0)
首先,您需要使代码请求看起来像您的curl请求。
您未指定请求的类型,并且缺少了与curl请求一起使用的标头。默认情况下,如果未指定(我没有使用过web3),大多数http库将使用GET请求,这就是您对web3所做的事情。
我首先将请求和标头添加到您的web3请求中。 这是使用httpheaderprovider的示例 (来源:https://github.com/EthereumEx/httpheaderprovider)
var Web3 = require('web3');
var web3 = new Web3();
var HttpHeaderProvider = require('httpheaderprovider');
var headers = {
"Ocp-Apim-Subscription-Key": "mykeyfromtheapiportal",
"header2": "foobar"
}
var provider = new HttpHeaderProvider('https://scicoria.azure-api.net', headers);
web3.setProvider(provider);
var coinbase = web3.eth.coinbase;
console.log(coinbase);
var balance = web3.eth.getBalance(coinbase);
console.log(balance.toString(10));
另请参阅