This.http.post error Response with status: 0 for URL: null


#1

I got error, When I try to call api.
I test the app at ionic lab -c.

url is my Vhost server in my computer.

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

@Injectable()
export class Api {
  url: any = 'http://myurl.local/api/';

  headers = new Headers(
  {
    'Content-Type' : 'application/json'
  });
  options = new RequestOptions({ headers: this.headers });

  constructor(public http: Http) {
    console.log('Hello API Provider');
  }

  login(username, password) {
    console.log('/////////// API Login //////////////');
    let data = {
      'service' : 'login',
      'login_type' : 1,
      'username' : username,
      'password' : password
    };
    let fullUrl = this.url+'login';
    console.log(fullUrl, data);
    return new Promise((resolve, reject) => {
      this.http.post(fullUrl, data, this.options)
      .toPromise()
      .then((response) =>
      {
        console.log('API Response : ', response);
        resolve(response.json());
      })
      .catch((error) =>
      {
        console.error('API Error : ', error.toString());
        reject(error.json());
      });
    });
  }
}

That is error i got.

[11:30:57]  console.log: /////////// API Login ////////////// 
[11:30:57]  error opening ws message: 
            {"category":"console","type":"log","data":["http://myurl.local/api/login",{"service":"login","login_type":1,"username":"XXXXXX","password":"XXXXXXX"}]}
[11:30:57]  console.error: API Error : Response with status: 0 for URL: null 

But in my API server, I already add 'Access-Control-Allow-Origin' => '*' in my code.
I try to read some forum, But i am not under stand it.

Cordova CLI: 6.5.0
Ionic Framework Version: 3.1.0
Ionic CLI Version: 2.2.3
Ionic App Lib Version: 2.2.1
Ionic App Scripts Version: 1.3.5
ios-deploy version: 1.9.1
ios-sim version: 5.0.13
OS: macOS Sierra
Node Version: v6.9.5
Xcode version: Xcode 8.3.2 Build version 8E2002


#2

I’m confused as to why you’re trying to set CORS headers on the client. I thought those are supposed to be managed by the server. I also see absolutely no reason for you to be explicitly instantiating a Promise.


#3

This function was in providers, I call it from my page function and wait for response.


#4

What is the request to and response from your server? Use dev tools to look at the headers and body of the messages - something is probably wrong in there.