Axios(在React-native中)不在localhost

时间:2017-02-12 15:16:44

标签: node.js react-native axios

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

我很绝望:-(在这里度过的时间过得太快了。如果你能帮帮我的话,请你......

这是我的代码LogIn页面。它派遣动作创建者(使用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与我在邮递员中使用的完全相同。 ......但是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调用给出的消息('无法登录')

我在Windows 10上,有:

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

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

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

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

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

11 个答案:

答案 0 :(得分:19)

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

要解决这个问题,我必须按以下方式发送请求:

https://10.0.2.2:3000/v1/test

而不是:

https://localhost:3000/v1/test

答案 1 :(得分:5)

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

    http://192.168.43.49:3000/user/

答案 2 :(得分:3)

如果您使用的是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));

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是从虚拟机到计算机的本地主机,但是没有用。

答案 3 :(得分:1)

我找到了axios的另一个解决方案。在反应原生问题上没有工作:

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

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

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

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

如果你的模拟器没有互联网连接,并且显示错误,例如:DNS探测完成了错误的配置,那么 停止ANDROID STUDIO仿真器并在终端

中运行这两个命令

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​

答案 4 :(得分:1)

对我来说“https://10.0.2.2:3000”不起作用。我尝试通过 ngrok 将 localhost:3000 映射到 URL 并使用该 URL
./ngrok http 3000(在终端上运行此命令将启动会话,全局 URL 映射到本地主机端口 3000)

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

答案 5 :(得分:0)

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

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

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

ipconfig

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

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

}; };

它现在应该可以工作!

答案 6 :(得分:0)

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

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

上运行 ipconfig 来获取IP地址

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

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

我没有在Linux和Mac OS上对其进行测试,但是它在Windows上可以正常运行!

答案 7 :(得分:0)

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

答案 8 :(得分:0)

我也遇到过类似的问题,并且我正在使用Expo CLI来构建和运行我的React Native应用程序。我的后端Express API也正在同一台计算机上运行。因此,在我的情况下,由于哪个localhost调用失败,所以从Android虚拟设备仿真器内部执行了Axios调用。因此,我没有使用本地主机,而是使用了IP地址,并且可以正常工作!

如果您使用的是expo客户端,请在Metro Server Page上检查热点IP地址,例如192.168.x.x(在我的情况下ip为这种类型)。

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

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

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

答案 9 :(得分:0)

Alternate way to solve this issue(如果以其他方式连接不起作用)。正如其他人所说,由于电话是另一台计算机,因此不能使用localhost。但是您可以使用隧道。这将为您提供一个复制本地主机的URL(向整个Internet开放)。

  1. 全局安装软件包localtunnel(在全局范围内添加全局添加纱线)
  2. 确保服务器正在运行,并记下端口(例如,http:// localhost:8081)
  3. 在另一个终端/命令提示符下,运行localtunnel命令(对我来说,这是npx localtunnel --port 8081)。这将创建您的服务器,您可以从开放的网络中访问它。
  4. 您现在可以使用控制台中的网址替换本机应用程序中的网址

我希望这对某人有帮助。

答案 10 :(得分:0)

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