反应本地网络请求失败错误

时间:2019-04-26 17:29:34

标签: react-native

我目前是React Native的新手,并且正在尝试构建简单的注册页面。但是,当我在我的应用程序上单击“注册”按钮时(它将用户插入服务器上的MySQL表中),但是在控制台上它说网络请求失败。我已经被这个错误困扰了好几天了,但是还没有找到有效的解决方案。使用axios代替fetch时也会出现“网络错误”。这是在Android设备上测试的。

这是错误:

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

我尝试过的事情:

  1. 用我的IP地址替换fetch / axios网址,但不起作用
  2. 使用我的服务器主机IP地址
  3. https://github.com/facebook/react-native/issues/5222#issuecomment-170239302
  4. React Native Post Request via Fetch throws Network Request Failed

这是我的提取内容:

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

    }

这是我的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);
      });

这是我设置后端的方式:

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

由于我仍然是本机反应,所以我的编码中可能会出现错误。如果需要显示更多代码,请告诉我。这个错误使我精神错乱!

1 个答案:

答案 0 :(得分:0)

我只是通过一系列步骤解决了这个问题。只花了两天的精神错乱。 :D请注意我的环境。

环境

  • 设备:ios iphone XS Max
  • 技术堆栈
    • backend = mongodb地图集,节点,表达
    • frontend = react-native,打字稿
    • dev env = expo-cli

调试步骤

  • 在MongoDB上,将“网络访问”设置为0.0.0.0/0。这样一来,任何请求都可以访问数据库。它包括您当前的IP地址。默认情况下,当您将IP地址列入白名单时,mongodb会在白名单IP地址的末尾添加/32。将其切换为/32而不是/0。或者只是授予所有人0.0.0.0/0
  • 在前端配置中,将API_BASE_URL设置为设备的IP地址,而不是localhost。 为此,您想在expo-cli上启动项目并查看设备IP地址。例如192.168.1.xxx。然后,您要像这样设置前端config.js

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"
};
相关问题