首页 > 解决方案 > 将Android模拟器上的本机反应连接到表达服务器

问题描述

我刚刚开始使用原生反应,我可以使用 Expo XDE 运行它。前端工作正常,但是当客户端(模拟器)向服务器(nodejs-express)发送“GET”请求时出现问题。

出现网络错误,如何将模拟器连接到express服务器?我使用了localhost ip,这是正确的方法吗?错误是关于我的手机和我的电脑之间的连接。我使用了localhost ip,但是当我用计算机本地ip替换它时,它就可以了。此外,如果您使用 android studio,您可以使用 10.0.0.2 或 10.0.0.3 进行 genymotion。

客户

 import React from "react";
 import { StyleSheet, Text, View, Button } from "react-native";
 import axios from "axios";

 export default class App extends React.Component {
  fetchData() {
    alert("clicked");
    axios
        .get("http://localhost:3000")
        .then(function(res) {
            console.log("success");
        })
        .catch(function(err) {
            console.log(err);
        });
}

render() {
    return (
        <View style={styles.container}>
            <Text>Open up App.js to start working on your app!</Text>

            <Button
                onPress={this.fetchData}
                title="Learn More"
                color="#841584"
                Label="Learn more"
            />
        </View>
    );
}
}

const styles = StyleSheet.create({
container: {
    flex: 1,
    backgroundColor: "#fff",
    alignItems: "center",
    justifyContent: "center"
}
});

服务器

   const express=require('express');
const bodyParser=require('body-parser')
var Port=process.env.PORT||3000;

const app=express();
app.use(bodyParser.json);
app.use(bodyParser.urlencoded({extended:false}));
app.listen(Port,()=>console.log(`server started at 3000`));

app.get('/',(req,res)=>{
    //res.send({data:"data"})
    console.log(console.log("request is recieved"))
})

标签: expressreact-nativeandroid-emulator

解决方案


推荐阅读