Axios (in React-native) not calling server in loca

2020-01-30 06:21发布

问题:

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:

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


回答2:

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.



回答3:

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!



回答4:

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​



回答5:

Another solution is to create a hosted network on the 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!



回答6:

Try Turning off your firewall it worked for me