43

I'm building a really easy api and react-native application. The server works well (tested with PostMan) but the application doesn't call the server. It blocks when axios has to send the post request (see below).

I'm desperate :-( Loosing too mush time in it. Please, if you can help me...

Here is my code LogIn page. It dispatch the action creator (working with redux) giving email and password:

...
const LogIn = React.createClass({
  submitLogin() {
    // log in the server
    if (this.props.email !== '' && this.props.psw !== '') {
      if (this.props.valid === true) {
        this.props.dispatch(logIn(this.props.email, this.props.psw));
      } else {
        this.props.dispatch(errorTyping());
      }
    }
  },
...

email and password are weel retrieved and sent to the action creator:

import axios from 'axios';
import { SIGNIN_URL, SIGNUP_URL } from '../api';
// import { addAlert } from './alerts';
exports.logIn = (email, password) => {
  return function (dispatch) {    
    console.log(email);
    console.log(password);
    console.log(SIGNIN_URL);
    return axios.post(SIGNIN_URL, { email, password })
    .then(
      (response) => {
        console.log(response);
        const { token, userId } = response.data;
        dispatch(authUser(userId));
      }
    )
    .catch(
      (error) => {
        console.log('Could not log in');
      }
    );
  };
};
const authUser = (userId) => {
 return {
 type: 'AUTH_USER',
 userId
 };
};
...

The three console.log() before axios show the data in the correct way. SIGNIN_URL is exactly the same I use in postman. ...but axios doesn't call.

Just to give all the cards, this is my store:

import thunk from 'redux-thunk';
import { createStore, compose, applyMiddleware } from 'redux';
import { AsyncStorage } from 'react-native';
import { persistStore, autoRehydrate } from 'redux-persist';
import reducer from '../reducer';
const defaultState = {};
exports.configureStore = (initialState = defaultState) => {
 const store = createStore(reducer, initialState, compose(
 applyMiddleware(thunk),
 autoRehydrate()
 ));
 persistStore(store, { storage: AsyncStorage });
 return store;
};

There's no error message in the debugger (but the one given by the axios call ('Could not log in')

I'm on windows 10, with:

"axios": "^0.15.3",
"react": "15.4.2",
"react-native": "0.38.0",
"redux": "^3.6.0"

The call fails even when I prepare a simple GET call and the server is supposed to give back a simple message (tested with postman and browser):

exports.test = () => {
  return function () {
    return axios.get('https://localhost:3000/v1/test')
    .then(
      (response) => {
        console.log(response);
      }
    )
    .catch(
      (error) => {
        console.log('error');
      }
    );
  };
};

Last, I tryed also to modify the call adding a header as the following, because the api is coded to accept json:

const head = {
  headers: { 'Content-Type': 'application/json' }
};

exports.test = () => {
  return function () {
    return axios.get('https://api.github.com/users/massimopibiri', head)
    .then(
      (response) => {
        console.log(response);
      }
    )
    .catch(
      (error) => {
        console.log('error');
      }
    );
  };
};

but even this didn't work. hope somebody can help me. Other similar issues didn't.

1
  • Extra infos: I'm working with android Commented Feb 12, 2017 at 15:19

13 Answers 13

73

The solution came from a different source, but I post it here to help others looking for the same issue. Basically I used Android AVD (emulator) to build the application. But the emulator is in fact another machine, and that's why it couldn't call the localhost.

To solve the probleme, I had to send the request in the following way:

https://10.0.2.2:3000/v1/test

instead of:

https://localhost:3000/v1/test
Sign up to request clarification or add additional context in comments.

9 Comments

your localhost certifcate is self signed ? How have you managed to call localhost without having a certfile path validation error ?
I didn't have to do any other change beside the one I wrote. it worked at the first try. So I don't know how to help you. What does it say the error message?
I am getting java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. because I a using a self signed certificate on localhost
I had this same issue with a Vue.js 2.0 application. On my laptop from which it was being served, my backend server was communicating no problem. However, when I tried to access on mobile I too was not getting any response from my backend. I had to change axios's settings as noted to target my local machine (192.168.1.7) in order for it to successfully reach my backend server. Thanks for this.
I can't get this to work my ip is 10.0.0.155 and I'm running IIS Express on localhost:44327. I put in the ipv4 address with the port 44327 for https and also tried the http port. Nothing works.
|
30

if u are using mac this solution worked for me. I am using React Native with Android Simulator ADV. Nexus Api 27

            axios.get('http://192.168.1.21:8686/api/v1/test')
            .then(response => console.log(response))
            .catch(err => console.log(err));

where the ip 192.168.1.21 is from system preferences > Network > Advanced > TCP/IP > IPv4 Address

I also tested axios.get('http://10.0.2.2:8686/bec/api/v1/test') where 10.0.2.2 is localhost from virtual machine to the computer but not worked.

1 Comment

thank you so much, this worked for me. I was sat for an hour thinking my API was broken because it would work with some sample API I found online but not my localhost one. thank you
15

Your Emulator is a device on it's own that is not running on the same IP(localhost or 127.0.0.1) as your web browser, postman or your server.

In order to make request to your server from your emulator you need to access your server via your computer IP Address: On windows get your IP Address by running ipconfig on the command prompt

On Unix terminal (Linux, Mac OS) run ifconfig to get your IP Address

Instead of http://localhost:port you should use http://your_ip_address:port

I didn't test it on Linux, Mac OS but its working perfectly on windows!

1 Comment

That's what called a pro, saw a lot of answers in different questions, you didn't mention any code but your explanation solved this issue
14
  1. change from localhost to your ip
  2. add http://

    http://192.168.43.49:3000/user/

1 Comment

This worked for me because I was using my android mobile device to debug the application, The android device doesn't have any idea of the localhost on my computer. So if you are using your android device to debug use IP address instead of using localhost
3

Another solution is to create a hosted network on the localhost computer with these commands from admin cmd:

netsh wlan set hostednetwork mode=allow ssid=wifi_name key=wifi_password
netsh wlan start hostednetwork

Connect your device to the computer's hotspot then get the computer's ip by running:

ipconfig

Now get the IPV4 address and put it on the app's axios/fetch url,

axios.get('https://192.168.137.1:3000/api')
.then(
  (response) => {
    console.log(response);
  }
)
.catch(
  (error) => {
    console.log('error');
  }
);

and it should now work!

Comments

2

I found another solution to the axios.get not working in react native problem:

Problem:- Object not visible and error: unhandled promise. Network error Solution:-- Use below command:

=>>> npm install -g --save axios

instead of npm install --save axios i.e. Use -g.

And also check whether your emulator is having internet connection.

If your emulator is not having internet connection and is showing error such as: DNS probe finished bad config​., then STOP ANDROID STUDIO Emulator and run these two commands in terminal

1.>> C:\Users\Admin\AppData\Local\Android\sdk\emulator\emulator.exe -list-avds​

My Output:

  • Pixel_XL_API_27

After this step, you will get the name of avds.

example:- Pixel_XL_API_27​

Now run below command:-

2.>> C:\Users\Admin\AppData\Local\Android\sdk\emulator\emulator.exe -avd Pixel_XL_API_27 -dns-server 8.8.8.8​

Comments

2

Alternate way to solve this issue if connecting a different way doesn't work. As others have said, because the phone is a different machine you can't use localhost. But you can use a tunnel. This will give you a url (open to the whole internet) that replicates your localhost.

  1. Install the package localtunnel globally (yarn global add localtunnel)
  2. Make sure your server is running, and note the port (for example, http://localhost:8081)
  3. In another terminal/command prompt, run the localtunnel command (for me, this was npx localtunnel --port 8081). This will create your server that you can hit from the open web.
  4. You can now replace the url in your react-native app with the url from the console

Comments

1

I have also faced similar issue and I am using Expo CLI for building and running my React Native application. My backend Express API are also running on same machine. So in my case Axios call is executing from inside Android Virtual Device emulator due to which localhost call is failing. So instead of using localhost I have used IP address and it worked!

If you are using expo client, please check hotspot IP address like 192.168.x.x (in my case ip is of this type) something on Metro Server Page.

If you are not using expo, then check your IP address using following commands :

  • ipconfig /all (On Windows)
  • ifconfig -a (OnLinux/Mac)

And then in axios api call, use http://192.168.x.x and if you are using https then use https but mostly for development purpose, you can go with http. But make sure in production environment, it is always good to use https with your domain or subdomain for providing additional security.

Comments

1

For me 'https://10.0.2.2:3000' was not working. I tried to map the localhost:3000 to a URL by ngrok and used that URL
./ngrok http 3000 (running this command on terminal will start session with global URL mapped to localhost port 3000)

Remeber,For this you should have ngrok installed on your system

Comments

1

i tried many other solutions but they didnt work, so i tried to run my laravel api on same address as expo-cli was running on enter image description here

so i took same ip of expo 192...x and changing only the port for my laravel server php artisan serve --host=192.168.100.107 --port=8000 and in axios :

axios
                .get("http://192.168.100.107:8000/api/users")
                .then(({ data }) => {
                  /* navigation.navigate("SmsScreen"); */
                  console.log(data);
                })
                .catch((err) => console.log(err));

and now its working great

Comments

0

Adding Cors to my Express App worked for me.

I did an npm install cors in the terminal in my Express server folder.

And then I just randomly added the following 2 lines of code to my Express server.js file:

const cors = require('cors');
app.use(cors())

Oh and then I specified the exact port in all my axios requests like below:

axios.post('http://localhost:5000/api/users/login/')

Comments

0

My problem: some ports were working for an expo app while the desired one 4000 wasn't. I wondered why. After much time researching, I found the workaround on Linux Mint: the Firewall.

  1. Make sure you are connected over the same network and configured your server properly.

  2. Go to Menu and search for Firewall in the machine hosting your server.

  3. Turn status off or add a firewall rule through the plus icon at the left bottom corner.

  4. Select Simple configuration and put your port there.

firewall Done!

Comments

-1

Try Turning off your firewall it worked for me

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.