ionic app无法连接到localhost

时间:2017-03-09 03:30:48

标签: android http localhost ionic2

我正在开发一个项目,允许Android Built Ionic版本2应用程序通过Django Rest API创建用户并对Django开发站点进行身份验证。

使用ionic serve时,身份验证可以通过使用跨源资源共享(安装为Google Chrome插件)来实现。

由于我尝试在实际的Android设备上运行应用程序,使用应用程序时身份验证失败(HTTP 404:找不到URL),但可以通过同一设备的浏览器访问localhost(通过192.168.22.4) :80)

详细信息:

我当前的私有IP地址是192.168.22.4,目前正在通过Wamp Apache Server在localhost端口80上提供开发站点。

以下是Ionic App(注册)上我的http请求的代码片段:

let headers = new Headers();
      headers.append('Content-Type','application/json');

      this.http.post("http://192.168.22.4:80/api-user-create", JSON.stringify(this.postData), {headers: headers}).subscribe(res => {
        console.log(res.json());
        this.showAlert();
      }, (err) => {
        console.log(err);
      });

应用解决方案:

这些是我尝试但仍无法连接到localhost的步骤:

  1. 确保允许该应用访问WiFi连接,验证我的IP地址是否正确,关闭防火墙甚至是我的防病毒软件。我还在我的开发服务器上启用了网络发现。
  2. 使用代理服务器(ngrok)并编辑离子请求
  3. 在Apache服务器上启用CORS并编辑离子请求
  4. 编辑离子请求代码。我试图将192.168.22.4:80更改为:
    • 192.168.22.4
    • 127.0.0.1:80
    • 127.0.0.1
    • localhost:80
    • localhost
    • 10.0.2.2
    • 10.0.2.2:80
  5. 有没有人遇到过这个问题并解决了?

1 个答案:

答案 0 :(得分:2)

问题解决了! 我通过以下方式解决了这个问题:

  1. 让wamp听听< ip address>:<端口号>。默认情况下,它最初设置为0.0.0.0:80。为了配置,我更新了我的wamp服务器上的httpd.conf,然后添加了以下行: Listen 192.168.22.4:80
  2. 在我的离子项目上安装cordova-plugin-whitelist。要做到这一点,我必须运行: cordova plugin add cordova-plugin-whitelist --save
  3. 编辑我的Ionic代码并删除请求中的端口号:

      let headers = new Headers();
      headers.append('Content-Type','application/json');
    
      this.http.post("http://192.168.22.4/api-user-create", JSON.stringify(this.postData), {headers: headers}).subscribe(res => {
        console.log(res.json());
        this.showAlert();
      }, (err) => {
        console.log(err);
      });
    
  4. 重建并运行应用程序

  5. 阅读Ionic App - No Internet Access了解详情。

相关问题