trufflesuite / truffle-hdwallet-provider

HD Wallet-enabled Web3 provider
MIT License
399 stars 167 forks source link

Cross-domain solution of web3.js request provider #88

Open xiaolujidan opened 5 years ago

xiaolujidan commented 5 years ago

I used nginx reverse proxy to deal with cross-domain problems, but web3.js request https://xxx.xxx/5b44529e903c4ebf9d60e4d01c965489 throw "Uncaught Error: Can't autodetect provider for "xxx.xxx/5b44529e903c4ebf9d60e4d01c965489""

The cross-domain configuration of nginx is as follows

location /5b44529e903c4ebf9d60e4d01c965489{

if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';

    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain; charset=utf-8';
    add_header 'Content-Length' 0;
    return 204;
 }
 if ($request_method = 'POST') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
 }
 if ($request_method = 'GET') {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
 }

proxy_pass https://mainnet.infura.io/v3/5b44529e903c4ebf9d60e4d01c965489;
}

web3.js code

import data from './abi'
import Web3 from 'web3';
export default {
    install: function (Vue, options) {
         var web3 = window.web3;
        var contract = '';
        //web3 = new Web3("https://mainnet.infura.io  /v3/5b44529e903c4ebf9d60e4d01c965489");
        web3 = new Web3("www.xxx.xxx/5b44529e903c4ebf9d60e4d01c965489");
        contract = new web3.eth.Contract(data.abi, data.address);
        Vue.prototype.infuraContract = contract;
        Vue.prototype.infuraWeb3 = web3;
        //Web3 version "web3": "^1.0.0-beta.36";
    }
}