express 端口 3000,react native 端口 8081,如何发出 get 请求

port 3000 for express, port 8081 for react native, how to make get request

我正在使用 React Native 作为我想要部署到 iOS 和 Android 的头像生成器。我正在为我的服务器使用 Express,它使用 localhost:3000,react native 使用 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 调试器中收到以下错误

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)

在android模拟器中,localhost指的是android系统。您使用 10.0.2.2 来引用它。例如。 http://10.0.2.2:3000 ()

虽然在 iOS 模拟器中,localhost 确实指的是主机:How do I access the host machine itself from the iPhone simulator

在本地测试时,您可能需要执行一些 platform-specific 逻辑,例如:

import { Platform } from 'react-native';

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

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