【问题标题】:port 3000 for express, port 8081 for react native, how to make get request端口 3000 用于 express,端口 8081 用于响应本机,如何发出 get 请求
【发布时间】:2017-02-08 23:12:39
【问题描述】:

我正在将 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>);}}

我在反应原生调试器中收到以下错误

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 ios express react-native native-base


    【解决方案1】:

    在安卓模拟器中,localhost指的是安卓系统。您使用10.0.2.2 来引用它。例如。 http://10.0.2.2:3000 (How 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/`)
        // ...
    

    【讨论】:

      猜你喜欢
      • 2018-01-13
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      相关资源
      最近更新 更多