0
votes

I am currently new in react native and on my way in attempting to build a simple register page. However when i hit signup button on my app(it should insert the user into my MySQL table on a server), but on console it says network request failed. I have been stuck on this error for days but have not come to a working solution. I also get "network error" when using axios instead of fetch This is tested on an android device.

Here is the error:

Network request failed
- node_modules\react-native\Libraries\vendor\core\whatwg-fetch.js:504:29 in onerror
- node_modules\event-target-shim\lib\event-target.js:172:43 in dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:578:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:392:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:191:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:349:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106:26 in <unknown>
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105:17 in callFunctionReturnFlushedQueue

What i have tried:

  1. Replacing the fetch/axios url with my ip address but doesnt work
  2. Using my server host ip address
  3. https://github.com/facebook/react-native/issues/5222#issuecomment-170239302
  4. React Native Post Request via Fetch throws Network Request Failed

Here is how my fetch looks like:

RegisterUser(){

    const url = 'https://myipAddressORserverIP:3210/data';
    fetch(url, {
       method: 'POST',
       headers: 
       {
         Accept: 'application/json',
        'Content-Type': 'application/json',
       },
       body: JSON.stringify(
       {
        username: this.state.name,
        email: this.state.email,
        password: this.state.password

       }),
       }).then(function (response) {
          console.log(response);
       }).catch(function (error) {
         console.log(error);
       });

    }

Here is my axios:

      var url = 'https://localhost:3210/data';

      axios.post(url, {
        username: this.state.inputusername,
        email: this.state.inputemail,
        password: this.state.inputpassword},
        { headers: {'Content-Type': 'application/json'}
      })
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });

This is how i setup my backend:

const db = mysql.createConnection({
    host:'**.***.**.***',
    user:'root',
    password:'*****',
    database: '*****'
});

db.connect(function(err) {
    if(!!err){
      console.log('Error')
    }
    else{
      console.log('Connected')
    }
  });

app.get('/data', function(req,res){
var sql = 'SELECT * FROM users';
db.query(sql, (err, result)=>{
    if(err) throw err;
    console.log(result);
    res.send(result);
  });
});

app.post('/data', function(req, res){
    console.log(req.body); 
    var data = {username:req.body.username, email:req.body.email, password:req.body.password};
    var sql = 'INSERT INTO users SET ?';
    db.query(sql, data, (err, result)=>{
    if(err) throw err;
    console.log(result);
    res.send({
        status: 'Data inserted',
        username: req.body.username,
        email: req.body.email,
        password: req.body.password
    });
  });
});

app.listen(3210, ()=>{
    console.log('Server at port 3210')
});

Since i am still in react native, there could be a possibility of an error in my coding. If need more code shown, please let me know. This error is driving me to insanity!!

1

1 Answers

1
votes

I just fixed this issue on my end through a series of steps. It only took 2 days of insanity. :D Please note my environment.

Environment

  • device: ios iphone XS Max
  • tech stack:
    • backend = mongodb atlas, node, express
    • frontend = react-native, typescript
    • dev env = expo-cli

Debugging Steps

  • On MongoDB, set Network Access to 0.0.0.0/0. This makes it so any request can access the database. It includes your current IP address. By default, when you whitelist an IP address mongodb adds /32 at the end of the whitelisted IP address. Instead of /32 switch it to /0. Or just give access to everyone 0.0.0.0/0
  • On the frontend config, set the API_BASE_URL to the IP address of your device instead of localhost. To do this, you want to start up your project on expo-cli and look at the device IP address. For example 192.168.1.xxx. Then you want to set your frontend config.jslike so:

client/config.js

module.exports = {
  PORT: process.env.PORT || 3050,
  API_BASE_URL: process.env.API_URL || 'http://192.168.1.xxx:8085',
}

server/config.js

module.exports = {
  PORT: process.env.PORT || 8085,
  DATABASE_URL:
    process.env.DATABASE_URL ||
    "mongodb+srv://<user>:<password>@clustername-5vu4d.mongodb.net/test?retryWrites=true&w=majority"
};