端口3000用于快速,端口8081用于反应本机,如何获取请求

时间:2017-02-08 23:12:39

标签: android ios express react-native native-base

我正在将React Native用于我要部署到iOS和Android的头像构建器。我正在为我的服务器使用Express,它使用localhost:3000,本机使用localhost:8081。

import axios from 'axios';
import React, { Component } from 'react';
import { AppRegistry, Text } from 'react-native';
import { Container, List, ListItem, Header, Title, Content, Thumbnail } from 'native-base';
import { Action } from 'react-native-router-flux';

export default class Class extends Component {
  componentWillMount(){
    axios.get('https://localhost:3000')
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
}

render() {
    return (
      <Container>
        <Header><Title>Choose Race</Title></Header>
        <Content> contents here <Content>);}}

我在react native debugger中收到以下错误

Error: Network Error
    at createError (createError.js:15)
    at XMLHttpRequest.handleError (xhr.js:87)
    at XMLHttpRequest.dispatchEvent (event-target.js:172)
    at XMLHttpRequest.setReadyState (XMLHttpRequest.js:542)
    at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:378)
    at XMLHttpRequest.js:482
    at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
    at MessageQueue.__callFunction (MessageQueue.js:236)
    at MessageQueue.js:108
    at guard (MessageQueue.js:46)

1 个答案:

答案 0 :(得分:4)

在android模拟器中,localhost指的是android系统。您可以使用10.0.2.2来引用它。例如。 http://10.0.2.2:3000How to connect to my http://localhost web server from Android Emulator in Eclipse

在iOS模拟器中,localhost确实引用了主机:How do I access the host machine itself from the iPhone simulator

在本地测试时,您可能必须执行一些特定于平台的逻辑,例如:

import { Platform } from 'react-native';

const host = Platform.select({
    ios: 'localhost',
    android: '10.0.2.2',
});

// ...
    axios.get(`http://${host}:3000/`)
    // ...