node.js Axios(在 React-native 中)不在本地主机中调用服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42189301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:00:04  来源:igfitidea点击:

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

node.jsreact-nativeaxios

提问by Pibo

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).

我正在构建一个非常简单的 api 和 react-native 应用程序。服务器运行良好(用 PostMan 测试),但应用程序不调用服务器。当 axios 必须发送 post 请求时它会阻塞(见下文)。

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:

这是我的代码登录页面。它派遣动作创建者(与 redux 一起工作)提供电子邮件和密码:

...
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.

axios 之前的三个 console.log() 以正确的方式显示数据。SIGNIN_URL 与我在邮递员中使用的完全相同。...但 axios 没有调用。

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')

调试器中没有错误消息(但是 axios 调用给出的错误消息('无法登录')

I'm on windows 10, with:

我在 Windows 10 上,使用:

"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):

即使我准备了一个简单的 GET 调用并且服务器应该返回一条简单的消息(用邮递员和浏览器测试),调用也会失败:

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:

最后,我还尝试修改调用,添加如下标题,因为 api 被编码为接受 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.

但即使这样也没有用。希望有人可以帮助我。其他类似的问题没有。

回答by Pibo

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.

该解决方案来自不同的来源,但我将其发布在这里是为了帮助其他人寻找相同的问题。基本上我使用 Android AVD(模拟器)来构建应用程序。但模拟器实际上是另一台机器,这就是它不能调用本地主机的原因。

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

回答by roll

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

如果您使用的是 mac,则此解决方案对我有用。我正在将 React Native 与 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.21is from system preferences > Network > Advanced > TCP/IP > IPv4 Address

ip192.168.1.21来自哪里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.2is localhost from virtual machine to the computer but not worked.

我还测试了从虚拟机到计算机的 localhostaxios.get('http://10.0.2.2:8686/bec/api/v1/test')在哪里,10.0.2.2但没有用。

回答by Peter Moses

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.

您的模拟器是一个独立的设备,与您的网络浏览器、邮递员或服务器不在同一 IP(本地主机或 127.0.0.1)上运行。

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 ipconfigon the command prompt

为了从您的模拟器向您的服务器发出请求,您需要通过您的计算机 IP 地址访问您的服务器:在 Windows上,通过在命令提示符下运行ipconfig来获取您的 IP 地址

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

在 Unix 终端(Linux、Mac OS)上运行ifconfig以获取您的 IP 地址

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

你应该使用http://your_ip_address:port而不是http://localhost :port

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

我没有在 Linux、Mac OS 上测试过它,但它在 Windows 上运行得很好!

回答by Akshay Vyas

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

我找到了另一个解决 axios.get 无法解决本机问题的解决方案:

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

问题:- 对象不可见和错误:未处理的承诺。网络错误解决方案:-- 使用以下命令:

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

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

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

而不是 npm install --save axios 即使用 -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

如果您的模拟器没有 Internet 连接并显示错误,例如:DNS 探测完成错误配置?,然后停止 ANDROID STUDIO 模拟器并在终端中运行这两个命令

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

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

My Output:

我的输出:

  • Pixel_XL_API_27
  • 像素_XL_API_27

?

?

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

在这一步之后,您将获得 avds 的名称。

example:- Pixel_XL_API_27?

示例:- 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?

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

回答by kamalesh biswas

  1. change from localhostto your ip
  2. add http://

    http://192.168.43.49:3000/user/

  1. 本地主机更改为您的ip
  2. 添加http://

    http://192.168.43.49:3000/user/

回答by Waweru wa Kamau

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

另一种解决方案是使用 admin cmd 中的以下命令在 localhost 计算机上创建托管网络:

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:

将您的设备连接到计算机的热点,然后运行以下命令获取计算机的 ip:

ipconfig

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

现在获取 IPV4 地址并将其放在应用程序的 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!

它现在应该可以工作了!

回答by user8572385

Try Turning off your firewall it worked for me

尝试关闭对我有用的防火墙