状态响应:0 for URL: null – 当我在模拟器或网络中 运行 时出现此错误

Response with status: 0 for URL: null – getting this error when I run in simulator or web

我正在使用 Ionic 框架开发一个基于 android 的简单移动女佣应用程序,我正在使用 laravel 作为我的后端。当我在 web 或 android 模拟器中 运行 时,我收到“状态响应:0 for URL: null”这个错误。

我无法注册新用户,当我使用 POSTMAN 检查我的 restful API 它有效并且我可以注册新用户时。但是当我在模拟器中 运行 这个应用程序时,它会继续显示这个“状态响应:URL 为 0:空”错误。

 **auth-service.ts file**

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http'
import 'rxjs/add/operator/map';

let apiUrl = 'http://fypBackend.test/api/';

@Injectable({
  providedIn: 'root'
})
export class AuthServiceService {

  constructor(public http: Http) { }

  register(data){
    return new Promise((resolve, reject) => {
      let headers = new Headers();
      headers.append('Content-Type', 'application/json');

      this.http.post(apiUrl+'users', JSON.stringify(data), {headers: headers})
      .subscribe(res => {
        resolve(res.json());
      }, (err) => {
        console.log('Not Working')
        reject(err);
      });
    });
  }
}

**register.ts file**

import { Component} from '@angular/core';
import { NavController,LoadingController, ToastController } from '@ionic/angular';
import {AuthServiceService} from '../auth-service.service';


@Component({
  selector: 'page-register',
  templateUrl: './register.page.html',
  styleUrls: ['./register.page.scss'],
})
export class RegisterPage{
  loading: any;
  regData = {name: '', icNumber: '', email: '', 
            password: '', phone: '', address: '', 
            cityState: '', houseType: '', category:''};
  

  constructor(public navCtrl: NavController, public authService: AuthServiceService, public loadingCtr: LoadingController, private toastCtrl: ToastController) { }

  doSignup(){
    this.authService.register(this.regData).then((result)=>{
      this.loading.dismiss();
      this.navCtrl.pop();
    }, (err) => {
      this.presentToast(err);
    });
  }
  async presentToast(msg){
    const toast  = await this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'top',
      color: 'dark',
    });
    toast.present();
  }
}

**register.html file**
<ion-content padding>
  <h2>Register Here</h2>
  <form (submit) = "doSignup()">
    <ion-item>
      <ion-label stacked>Username</ion-label>
      <ion-input [(ngModel)] = "regData.name" name = "name" type="text" placeholder = "Your Name"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label stacked>IC-Number</ion-label>
      <ion-input [(ngModel)] = "regData.icNumber" name = "icNumber" type="number" placeholder = "Your IC-Number"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label stacked>E-mail</ion-label>
      <ion-input [(ngModel)] = "regData.email" name = "email" type="email" placeholder = "Your E-Mail"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label stacked>Password</ion-label>
      <ion-input [(ngModel)] = "regData.password" name = "password" type="password" placeholder = "Your Password"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label stacked>Handphone Number</ion-label>
      <ion-input [(ngModel)] = "regData.phone" name = "phone" type="tel" placeholder = "Your Phone Number"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label stacked>Address</ion-label>
      <ion-input [(ngModel)] = "regData.address" name = "address" type="text" placeholder = "Your Address"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label stacked>City/State</ion-label>
      <ion-input [(ngModel)] = "regData.cityState" name = "cityState" type="text" placeholder = "Your City/State"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label stacked>House Type</ion-label>
      <ion-input [(ngModel)] = "regData.houseType" name = "houseType" type="text" placeholder = "Your House Type"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label stacked>Category</ion-label>
      <ion-select [(ngModel)] = "regData.category" name = "category" type="text" placeholder = "Your Category">
        <ion-select-option value="1" selected>Maid</ion-select-option>
        <ion-select-option value="2" selected>Customer</ion-select-option>
      </ion-select>
    </ion-item>
    <button ion-button block type = "submit">
      SignUp
    </button>
  </form>
</ion-content>

这似乎是一个 CORS 问题,要避免 CORS 问题,您必须使用 @ionic-native/HTTP 插件,它实际上是用于 API 调用的高级 HTTP 插件。

按照以下步骤使用此插件

第 1 步:添加 Http 原生插件

$ ionic cordova plugin add cordova-plugin-advanced-http
$ npm install --save @ionic-native/http
Installation Link : HTTP

第 2 步:在您要调用的文件中导入 HTTP 本机插件 API。

import { HTTP, HTTPResponse } from '@ionic-native/http';
Step 3: How to use this plugin for API call ?

constructor(public httpPlugin: HTTP) {

  }

//Set header like this
this.httpPlugin.setHeader("content-type", "application/json");

//Call API 
this.httpPlugin.get(this.url, {}, {}).then((response) => {
    //Got your server response
}).catch(error => {
    //Got error 
});