Reputation: 25
I am using React Native for an avatar builder that I want to deploy to iOS and Android. I am using Express for my server, which uses localhost:3000, react native uses 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>);}}
I get the following error in the 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)
Upvotes: 1
Views: 1310
Reputation: 1008
In the android emulator, localhost
refers to the android system. You use 10.0.2.2
to refer to it. E.g. http://10.0.2.2:3000
(How to connect to my http://localhost web server from Android Emulator in Eclipse)
In the iOS emulator though, localhost
does refer to the host machine: How do I access the host machine itself from the iPhone simulator
You will probably have to do some platform-specific logic while you test locally, example:
import { Platform } from 'react-native';
const host = Platform.select({
ios: 'localhost',
android: '10.0.2.2',
});
// ...
axios.get(`http://${host}:3000/`)
// ...
Upvotes: 4