1

我正在开发一个 ionic-angular 应用程序,并且在使用 ionic serve 在浏览器上进行测试时发布请求工作正常,但是在安卓设备或模拟器上执行时,请求不起作用。

后端是在 windows 服务器上使用 slim php 和 xampp 的 rest api

android设备中请求的响应是:

{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http:// /<>/ws_login.php/login","ok":false,"name":"HttpErrorResponse","message":"http://<>/ws_login.php/login 的 Http 失败响应:0 未知错误","错误":{"isTrusted":true}}

我的登录代码如下所示:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClientModule, HttpClient, HttpHeaders } from '@angular/common/http';
import { AuthConstants } from '../config/auth-constants';
import { ToastService } from './../services/toast.service';
import { LoadingService } from './../services/loading.service';
import { StorageService } from './../services/storage.service';
import { environment } from '../../environments/environment';

@Component({
    selector: 'app-login',
    templateUrl: './login.page.html',
    styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
    data = {
        user : '',
        pass : ''
    }

    constructor(
        public http: HttpClient, 
        private router: Router, 
        private toastService: ToastService,
        private loadingService: LoadingService,
        private storageService: StorageService
    ) { }

    ngOnInit() {
        this.storageService.get(AuthConstants.AUTH).then(
            data => data?this.router.navigate(["home"]):null
        )
    }

    login() {
        var headers = new HttpHeaders();
        headers.append("Accept", 'application/json');
        headers.append('Content-Type', 'application/json' );
        const requestOptions = { headers: headers };

        if(this.data.user == "" || this.data.pass == "")
            return this.toastService.presentToast("Debe completar ambos campos", "danger");

        this.loadingService.showLoading("Iniciando sesión");
        console.log(environment.apiUrl+'ws_login.php/login');
        this.http.post(environment.apiUrl+'ws_login.php/login', this.data, requestOptions).subscribe(
            resp => {
                this.loadingService.hideLoading();
                if(resp){
                    if(resp['error'] == 1)
                        this.toastService.presentToast(resp['mensaje'], "danger");
                    else{
                        this.storageService.store(AuthConstants.AUTH, 1);
                        this.toastService.presentToast("Sesión iniciada con éxito", "success");
                        this.router.navigate(["home"]);
                    }
                }
                else
                    this.toastService.presentToast("Error de red", "danger");
            }, 
            error => {
                this.data.user = JSON.stringify(error);
                this.loadingService.hideLoading();
                this.toastService.presentToast("Error de red", "danger");
            }
        );/*
        console.log(AuthConstants.AUTH);
        AuthConstants.AUTH = {id: 1};*/
        //this.router.navigate(["home"]);
    }
}

我还使用设备上的 rest 应用程序测试了 api,并且相同的 url 答案没有问题。

我将 android:usesCleartextTraffic="true" 添加到 androd manifest 并不是解决方案。

这里 mi ionic 信息

Ionic:

   Ionic CLI                     : 6.3.0 (C:\Users\Manu\AppData\Roaming\npm\node_modules\@ionic\cli)
   Ionic Framework               : @ionic/angular 5.0.7
   @angular-devkit/build-angular : 0.803.26
   @angular-devkit/schematics    : 8.3.26
   @angular/cli                  : 8.3.26
   @ionic/angular-toolkit        : 2.2.0

Capacitor:

   Capacitor CLI   : 2.0.0
   @capacitor/core : 2.0.0

Utility:

   cordova-res : 0.11.0
   native-run  : 0.3.0

System:

   NodeJS : v12.16.1 (C:\Program Files\nodejs\node.exe)
   npm    : 6.13.4
   OS     : Windows 10

谢谢!

4

4 回答 4

1

由于错误表明您正在发布到http://<>/ws_login.php/login,我猜您的环境变量 apiUrl 中存在错误,当您部署到移动设备时。如果您在开发人员机器上提供应用程序,则需要 environment.ts 来获取变量。也许您在生产中为您的手机构建了应用程序,因此没有获得正确的环境变量(因为 Ionic 然后使用 environment.prod.ts?

于 2020-04-17T05:43:10.523 回答
0

您可以使用移动设备https://ionicframework.com/docs/native/http尝试 ionic Advance HTTP ,但它不适用于 Web 浏览器,它仅适用于移动设备。因此您可以尝试解决方案来检查平台并根据用户平台返回 HTTP 服务对象。例如:如果用户平台==web 则返回 Angular HttpClient 否则如果用户平台==Android/Ios 则返回 Advnace Http 对象。

或者您可以直接使用此代码,该代码具有 HTTP 服务的包装器,

import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { HttpClient } from '@angular/common/http';
import { HTTP } from '@ionic-native/http/ngx';
import { from, observable, Observable, of } from 'rxjs';
import { environment } from './../../environments/environment';
import { map, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class HttpService {

  constructor(private platform: Platform, private httpclient: HttpClient, private http: HTTP) {
  }

  HttpRequest(method: 'POST'|'GET', url: string, requestBody: any): any
  {

    url = environment.serverBaseUrl + url;

    const headers = {};

    if (this.platform.is('ios') || this.platform.is('android') || this.platform.is('mobile'))
    {
    if (method === 'POST')
    {
      console.log('Advance_HTTP_POST');
      return from(this.http.post(url, requestBody, headers)).pipe(map((data: any) => JSON.parse(data?.data)));
    } else if (method === 'GET')
    {
      console.log('Advance_HTTP_GET');
      return from(this.http.get(url, {}, headers)).pipe(map((data: any) => JSON.parse(data?.data)));
    }
  } else {
    if (method === 'POST')
    {
      console.log('HTTPClient_HTTP_POST');
      return this.httpclient.post(url, requestBody, {headers});
    } else if (method === 'GET')
    {
      console.log('HTTPClient_HTTP_GET');
      return this.httpclient.get(url, {headers});
    }
    }
  }
}

于 2020-09-23T05:15:56.283 回答
0

显然,angular httpClient 在本机设备和模拟器上执行时存在一些问题,我的解决方案是将请求迁移到 ionic native http。

谢谢您的帮助!

于 2020-04-18T04:37:57.927 回答
0

我面临着同样的问题。就我而言,我正在做一个PROD build并且该environment.prod.ts文件没有托管的 API 链接。

我按照以下步骤解决了我的问题:

  1. 更新environment.prod.ts指向您托管 API 的文件链接。

    在此处输入图像描述

  2. 使用所需配置将您的 SPA 构建到www(在您的应用程序中配置的任何文件夹)文件夹。

  3. 如果是第一个实例,则添加平台 -npx cap add android

  4. 将资源复制到平台代码 -npx cap copy

  5. 如果添加了任何插件,请更新 android 应用程序 -npx cap update

  6. 打开安卓应用——npx cap open android

  7. 检查模拟器中的应用并测试 API 响应。

答对了!希望这可以帮助有需要的人。

于 2021-09-28T15:32:33.273 回答