React-Native 无法与我的 API 连接 - “错误:网络错误”

问题描述

我有一个错误,我不知道如何摆脱。我正在尝试使用 express 获取我的后端 API,但我唯一得到的是来自 android 模拟器的 Error: Network Error,我使用的是 Android Studio

这是一个非常简单的项目,因为我最近开始使用 react-native 编写代码

在我的 API 中,基本上有 express、cors,并且在端口 3333 上运行。

我的 react-native 项目:

api.js

import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:3333/'
})

export default api;

index.js

import React,{ useEffect,useState } from 'react';
import { View,Text,StyleSheet,StatusBar } from 'react-native';

import api from './services/api';

export default function App() {
  const [projects,setProjects] = useState([]);

  useEffect(() => {  
    api.get('projects').then(response => {
      console.log(response.data);
      setProjects(response.data);
    })

  },[])

  return (
    <>
    <StatusBar barStyle='light-content' backgroundColor='#7159c1'/>
    <View style={styles.container}>
      <Text style={styles.title}>Hello World!</Text>
    </View>
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,backgroundColor: '#7159c1',justifyContent: 'center',alignItems: 'center',},title: {
    color: '#fff',fontSize: 32,fontWeight: 'bold',}
})

我只想在控制台中返回路由 localhost:3333/projects 中的内容。 我已经尝试使用地址 10.0.2.2,我的 ipv4 来使用 localhost 我尝试了命令 adb reverse tcp:3333 tcp:3333 ,使防火墙失效,但我不知道该怎么办了。

完整错误

WARN     Possible Unhandled Promise Rejection (id: 0):
Error: Network Error
createError@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:99894:26
handleError@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:99798:27
dispatchEvent@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:32277:31
setReadyState@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:31367:33
__didCompleteResponse@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:31183:29
emit@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:3537:42
__callFunction@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2765:36
http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2497:31
__guard@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2719:15
callFunctionReturnFlushedQueue@http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false:2496:21
callFunctionReturnFlushedQueue@[native code]

我有 Windows 10。

编辑 1:我的朋友在他的 macbook 中运行了我的代码并且运行良好。那么可能是一些权限在 W10 阻止了我的后端?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)