连接在Android模拟器上本机响应以表达服务器

时间:2018-05-08 13:25:04

标签: express react-native android-emulator

我刚刚开始反应原生,我可以使用Expo XDE运行它。前端正常工作但客户端(模拟器)向服务器发送'GET'请求时出现问题(nodejs-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"))
})

0 个答案:

没有答案