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

Created on 17 Nov 2018  ·  7Comments  ·  Source: ChainSafe/web3.js

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-installrn-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?

support

Most helpful comment

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.

All 7 comments

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.

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

@nivida maybe it obvious question. I just installed web3 'npm i [email protected]'. Then I looked at 'node_modulesweb3-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?

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.

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

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);

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

TinyWJL picture TinyWJL  ·  3Comments

gabmontes picture gabmontes  ·  3Comments

joeriexelmans picture joeriexelmans  ·  3Comments

sundbry picture sundbry  ·  3Comments

xpepermint picture xpepermint  ·  3Comments