我正在用React Native开发一个简单的应用程序.我正在安卓设备上测试.我已经创建了一个 node .js服务器来监听请求,它的运行速度是http://localhost:3333/.

fetch('http://localhost:3333/', 
        {
            'method': 'GET',
            'headers': {
                'Accept': 'text/plain',                                     
            }
        }       
    ) 
.then((response) => response.text()) 
.then((responseText) => {
    console.log(responseText);  
}) 
.catch((error) => {
    console.warn(error);
}); 

node 服务器上的请求处理程序的代码如下所示

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
}); 
app.use(express.static('public'));
app.get('/', function(req, res){ 
    console.log('Request received for /');
    res.send("this is the response from the server");
    res.end();
});

但是,获取请求不起作用.我在Chrome控制台中遇到的错误是:

如何做到这一点?

推荐答案

因为你的安卓设备有自己的IP,你需要将URL指向你的计算机IP地址,而不仅仅是本地主机.例如fetch('http://192.168.0.2:3333/').

React-native相关问答推荐

元素类型无效:应为字符串

react-native-fs 改变 toUrl 本身

有人可以帮我实现 Font.loadAsync

如何将 react-native 图像从 expo-image-picker 上传到使用 multer 的 Express.js 后端

React Native - 何时调用componentWillUnmount?

ReactJS 应用多种内联样式

变量 window在react-native 中代表什么?

React中类似于 React Native 中的 FlatList

RNFS.exists() 总是返回 TRUE

修复错误:路由 'Home' 的组件必须是 React 组件

如何在 React Native 中访问原生 UI 组件的实例方法

cmd : react-native run-android 在每次文件更改时

react-native android应用程序中的underlineColorAndroid is not a valid style property错误

在特定屏幕上使用react-navigation修改后退按钮

组件div的视图配置 getter 回调必须是一个函数(收到 undefined)

XCode AppIcon 基于方案

React-native:图像未显示在 android 设备中,但在模拟器中完美显示

当前文件夹中的 react-native init

在 React Native ScrollView 中检测滚动结束,对齐页面

react-native:多色文本视图