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

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

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

我很绝望:-(浪费太多时间了。如果你能帮助我,请...

这是我的代码登录页面。它派遣动作创建者(使用 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());
      }
    }
  },
...

我们将检索电子邮件和密码并将其发送给操作创建者:

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

axios 前的三个console.log() 正确显示了数据。 SIGNIN_URL 与我在 postman 中使用的完全相同。 ...但是 axios 没有调用。

顺便给大家打卡,这是我的店铺:

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;
};

调试器中没有错误消息(但 axios 调用给出的错误消息 ('Could not log in')

我在 windows 10,有:

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

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

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

最后,我还尝试修改添加 header 的调用,如下所示,因为 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');
      }
    );
  };
};

但即使这样也行不通。希望有人能帮助我。其他类似问题没有。

解决方案来自不同的来源,但我 post 在这里帮助其他人寻找同样的问题。基本上我使用 Android AVD(模拟器)来构建应用程序。但模拟器实际上是另一台机器,所以它无法调用本地主机。

为了解决这个问题,我不得不通过以下方式发送请求:

https://10.0.2.2:3000/v1/test

而不是:

https://localhost:3000/v1/test

我找到了 axios.get not working in react native 问题的另一个解决方案:

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

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

而不是 npm install --save axios 即使用 -g.

还要检查您的模拟器是否有互联网连接。

如果您的模拟器没有互联网连接并且显示错误,例如:DNS probe finished bad config .,那么 STOP ANDROID STUDIO Emulator 和 运行 这两个命令在终端

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

我的输出:

  • Pixel_XL_API_27

完成此步骤后,您将获得avds的名称。

示例:- Pixel_XL_API_27

现在 运行 下面的命令:-

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

另一种解决方案是在本地主机计算机上使用管理员 cmd 中的这些命令创建托管网络:

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

将您的设备连接到电脑的热点,然后通过运行获取电脑的ip:

ipconfig

现在获取 IPV4 地址并将其放在应用程序的 axios/fetch url,

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

现在应该可以使用了!

如果您正在使用 mac,此解决方案对我有用。 我将 React Native 与 Android Simulator ADV 一起使用。联系 Api 27

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

ip 192.168.1.21 来自 system preferences > Network > Advanced > TCP/IP > IPv4 Address

我还测试了 axios.get('http://10.0.2.2:8686/bec/api/v1/test'),其中 10.0.2.2 是从虚拟 machine 到计算机的本地主机,但无法正常工作。

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

为了从您的模拟器向您的服务器发出请求,您需要通过您的计算机 IP 地址访问您的服务器: windows 在命令提示符

上通过 运行ning ipconfig 获取您的 IP 地址

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

代替http://localhost:port you should use http://your_ip_address:port

我没有在 Linux、Mac OS 上测试它,但它在 windows 上运行完美!

尝试关闭你的防火墙它对我有效

  1. localhost 更改为您的 ip
  2. 添加http://

    http://192.168.43.49:3000/user/

我也遇到过类似的问题,我正在使用 Expo CLI 构建和 运行 我的 React Native 应用程序。我的后端 Express API 也在同一台机器上 运行。因此,在我的情况下,Axios 调用是从 Android 虚拟设备模拟器内部执行的,因此 localhost 调用失败。因此,我没有使用 localhost,而是使用了 IP 地址,而且它起作用了!

如果您使用的是 expo 客户端,请检查热点 IP 地址,如 192。168.x.x(在我的情况下 ip 是这种类型)Metro 服务器页面上的一些内容。

如果您没有使用 expo,请使用以下命令检查您的 IP 地址:

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

然后在 axios api 调用中,使用 http://192.168.x.x,如果您使用 https,则使用 https,但主要用于开发目的,您可以使用 http。但请确保在生产环境中,将 https 与您的域或子域一起使用以提供额外的安全性总是好的。

Alternate way to solve this issue 如果以其他方式连接不起作用。正如其他人所说,因为 phone 是一台不同的机器,所以你不能使用本地主机。但是你可以使用隧道。这将为您提供一个 url(对整个互联网开放)来复制您的本地主机。

  1. 全局安装包localtunnel(yarn global add localtunnel)
  2. 确保您的服务器是 运行ning,并记下端口(例如,http://localhost:8081)
  3. 在另一个 terminal/command 提示中,运行 localtunnel 命令(对我来说,这是 npx localtunnel --port 8081)。这将创建您可以从开放网络访问的服务器。
  4. 您现在可以用控制台中的 url 替换您的 react-native 应用程序中的 url

我希望这对某人有所帮助。

对我来说 'https://10.0.2.2:3000' 没用。我试图通过 ngrok 将 localhost:3000 映射到 URL 并使用 URL
./ngrok http 3000(运行 终端上的此命令将启动与映射到本地主机端口 3000 的全局 URL 的会话)

记住,为此你应该在你的系统上安装 ngrok

将 Cors 添加到我的 Express 应用程序对我有用。

我在我的 Express 服务器文件夹中的终端中执行了 npm install cors

然后我随机将以下两行代码添加到我的 Express server.js 文件中:

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

哦,然后我在所有 axios 请求中指定了确切的端口,如下所示:

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

我的问题:某些端口适用于 expo 应用程序,而所需的 4000 则不行。我想知道为什么。经过大量研究,我在 Linux Mint:防火墙上找到了解决方法。

  1. 确保您通过同一网络连接并正确配置了您的服务器。

  2. 转到“菜单”并在托管服务器的计算机中搜索“防火墙”。

  3. 通过左下角的加号图标关闭状态或添加防火墙规则。

  4. Select简单的配置,把你的端口放在那里。

完成!