Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use web3 with react native, Invalid JSON RPC response: "Failed to connect to mainnet.infura.io #2054

Closed
jiangbo0216 opened this issue Nov 17, 2018 · 7 comments

Comments

@jiangbo0216
Copy link

I create a simple react native project following this:

1 init Project

react-native init lm1
cd lm1

2 npm intall

yarn add node-libs-browser
3 create rn-cli.config.js

const extraNodeModules = require('node-libs-browser');

module.exports = {
  extraNodeModules,
};

4 create global.js


global.Buffer = require('buffer').Buffer;
global.process = require('process');

if (typeof btoa === 'undefined') {
    global.btoa = function (str) {
      return new Buffer(str, 'binary').toString('base64');
    };
  }
  
  if (typeof atob === 'undefined') {
    global.atob = function (b64Encoded) {
      return new Buffer(b64Encoded, 'base64').toString('binary');
    };
  }

5 app.js import global

import './global';
6 npm install babel-preset-es2015

yarn add --dev babel-cli babel-preset-es2015

install react-native-crypto react-native-randombytes

yarn add react-native-crypto react-native-randombytes

install tradle/rn-nodeify
yarn add --dev tradle/rn-nodeify

link
react-native link

run command in cmd

./node_modules/.bin/rn-nodeify --hack --install

import in App.js

import './shim.js'
import crypto from 'crypto'

7 instal lweb3

yarn add web3
8 call web3 method


import Web3 from 'web3';


componentWillMount() {
    const web3 = new Web3(
      new Web3.providers.HttpProvider('https://mainnet.infura.io/')
    );
  
    web3.eth.getBlock('latest').then(console.log)
  }

9 log

react-native log-android
10 run in android

react-native run-android

if error occur
run this command
react-native link
re-install rn-nodefiy

yarn add --dev tradle/rn-nodeify

run again
./node_modules/.bin/rn-nodeify --hack --install

in project root directory, shim.js will appear.

I build this in window10,and my package.json is like this:

{
  "name": "rn_web3_test",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "@tradle/react-native-http": "^2.0.0",
    "bignumber.js": "^8.0.1",
    "browserify-zlib": "~0.1.4",
    "dns.js": "^1.0.1",
    "https-browserify": "~0.0.0",
    "node-libs-browser": "^2.1.0",
    "react": "16.6.1",
    "react-native": "0.57.5",
    "react-native-crypto": "^2.1.2",
    "react-native-level-fs": "^3.0.0",
    "react-native-os": "^1.0.1",
    "react-native-randombytes": "^3.5.1",
    "react-native-tcp": "^3.2.1",
    "react-native-udp": "^2.1.0",
    "readable-stream": "1.0.33",
    "stream-browserify": "^1.0.0",
    "string_decoder": "~0.10.25",
    "timers-browserify": "^1.0.1",
    "url": "~0.10.1",
    "web3": "^1.0.0-beta.36"
  },
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-jest": "23.6.0",
    "babel-preset-es2015": "^6.24.1",
    "jest": "23.6.0",
    "metro-react-native-babel-preset": "0.49.2",
    "react-test-renderer": "16.6.1",
    "rn-nodeify": "tradle/rn-nodeify"
  },
  "jest": {
    "preset": "react-native"
  },
  "react-native": {
    "zlib": "browserify-zlib",
    "console": "console-browserify",
    "constants": "constants-browserify",
    "crypto": "react-native-crypto",
    "dns": "dns.js",
    "net": "react-native-tcp",
    "domain": "domain-browser",
    "http": "@tradle/react-native-http",
    "https": "https-browserify",
    "os": "react-native-os",
    "path": "path-browserify",
    "querystring": "querystring-es3",
    "fs": "react-native-level-fs",
    "_stream_transform": "readable-stream/transform",
    "_stream_readable": "readable-stream/readable",
    "_stream_writable": "readable-stream/writable",
    "_stream_duplex": "readable-stream/duplex",
    "_stream_passthrough": "readable-stream/passthrough",
    "dgram": "react-native-udp",
    "stream": "stream-browserify",
    "timers": "timers-browserify",
    "tty": "tty-browserify",
    "vm": "vm-browserify",
    "tls": false
  },
  "browser": {
    "zlib": "browserify-zlib",
    "console": "console-browserify",
    "constants": "constants-browserify",
    "crypto": "react-native-crypto",
    "dns": "dns.js",
    "net": "react-native-tcp",
    "domain": "domain-browser",
    "http": "@tradle/react-native-http",
    "https": "https-browserify",
    "os": "react-native-os",
    "path": "path-browserify",
    "querystring": "querystring-es3",
    "fs": "react-native-level-fs",
    "_stream_transform": "readable-stream/transform",
    "_stream_readable": "readable-stream/readable",
    "_stream_writable": "readable-stream/writable",
    "_stream_duplex": "readable-stream/duplex",
    "_stream_passthrough": "readable-stream/passthrough",
    "dgram": "react-native-udp",
    "stream": "stream-browserify",
    "timers": "timers-browserify",
    "tty": "tty-browserify",
    "vm": "vm-browserify",
    "tls": false
  }
}

and I build apk successfully,and there is no obvious bug,
but I got this
undefined Error: Invalid JSON RPC response: "Failed to connect to rinkeby.infura.io
and this

Possible Unhandled Promise Rejection (id: 0):
Error: Invalid JSON RPC response: "Failed to connect to rinkeby.infura.io/35.169.193.102:80"
Error: Invalid JSON RPC response: "Failed to connect to rinkeby.infura.io/35.169.193.102:80"

the code run well in node , got the response

const Web3 = require("web3");
const BigNumber = require('bignumber.js');
const Ether = new BigNumber(10e+17);
let web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/'));
web3.eth.getBlock('latest', (err, block) => {
  console.log(block,err)
});

so is anyone met problem like this?

@jiangbo0216
Copy link
Author

I found in react-native ,use the buildt-in function XMLHttpRequest to replace require('xhr2-cookies').XMLHttpRequest and the code can do well.
and my solution as follow:

node_modules\web3-providers-http\src\index.js

// var XHR2 = require('xhr2-cookies').XMLHttpRequest // jshint ignore: line

HttpProvider.prototype._prepareRequest = function(){
    // var request = new XHR2();
    var request = new XMLHttpRequest();
    // request.nodejsSet({
    //     httpsAgent:this.httpsAgent,
    //     httpAgent:this.httpAgent
    // });

    request.open('POST', this.host, true);
    request.setRequestHeader('Content-Type','application/json');
    request.timeout = this.timeout && this.timeout !== 1 ? this.timeout : 0;
    request.withCredentials = true;

    if(this.headers) {
        this.headers.forEach(function(header) {
            request.setRequestHeader(header.name, header.value);
        });
    }

    return request;
};

is there any other solution,if there are some other,please contact me! thank you.

@6pm
Copy link

6pm commented Dec 16, 2018

@jiangbo0216 This solution works, but can it break anything related to cookies?

@6pm
Copy link

6pm commented Dec 16, 2018

@nivida maybe it obvious question. I just installed web3 'npm i web3@1.0.0-beta.37'. Then I looked at 'node_modules\web3-providers-http\src\index.js' and checked the same module on master branch
master/lib/web3/httpprovider.js
And they are different. How come?
How often do you update web3 npm module?
I was going to fork web3 and comment these lines then use it in my package.json as dependency instead of npm web3 module. Where I can find 1.0.0-beta.37?

@nivida
Copy link
Contributor

nivida commented Dec 17, 2018

Hay @6pm,
I apologize for the confusion but the current branch structure is as follows:

v0.20.x - develop/master branch
v1.0-x - 1.0 branch

This will be improved on the 1.0 stable release.

@jiangbo0216
Copy link
Author

@6pm My situation does not involve cookies, so I am not sure.if you have some
problems with cookies. welcome to complement

@jacksonng77
Copy link

I have a similar problem. My problem is that I am trying to connect to a private node that needs me to enter a URL in the format of https://username:password@nodeURL.

Doing this in node.js works.

global.web3 = new Web3(new Web3.providers.HttpProvider('https://u0qtldq5dw:LXXyYKKW22dAIP8S6olXARo3dd1DbF0KUXsyZRnliuo@u0yyyar44q-u0nczix681-rpc.us-east-2.kaleido.io'));

web3.eth.getBlock("latest").then((latestBlock) => {
    console.log("Latest Block Via HTTP Provider: ")
    console.log(latestBlock);
    // Stop the program once this has finished
    process.exit();
});

but doing the same in React-Native give me an error:

[12:43:01] [Unhandled promise rejection: Error: Invalid JSON RPC response: "<html>\r\n<head><title>401 Authorization Required</title></head>\r\n<body>\r\n<center><h1>401 Authorization Required</h1></center>\r\n<hr><center>nginx</center>\r\n</body>\r\n</html>\r\n"]
- node_modules\web3-core-helpers\src\errors.js:42:25 in InvalidResponse
- node_modules\web3-providers-http\src\index.js:73:47 in onreadystatechange
- ... 9 more stack frames from framework internals

I have attempted to do this to split the node URL, username and password to 3 different parameters but it doesn't work in Node nor React-Native.

let provider = new Web3.providers.HttpProvider('https://u0yyyar44q-u0nczix681-rpc.us-east-2.kaleido.io', 0, 'u0qtldq5dw', 'LXXyYKKW22dAIP8S6olXARo3dd1DbF0KUXsyZRnliuo');
let web3 = new Web3(provider);

@nivida
Copy link
Contributor

nivida commented Apr 16, 2019

Closed because of the ongoing clean up of the issue list. Feel free to ask this in our gitter channel or on stackoverflow.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants