Http request not working on android (working on ios/brower) ionic 4 angular 5


#1

I am new to ionic, and I think I have a standard http request set up.

import { HttpClient, HttpHeaders } from ‘@angular/common/http’;

const data = {audio: audioBytes};
return new Promise(resolve => {
this.http.post(‘http://localhost:3333/upload/’, JSON.stringify(data), {
headers: new HttpHeaders().set(‘Content-Type’, ‘application/json’)
})
.subscribe(data => {
resolve(data);
}, err => {
console.log("Error: ", JSON.stringify(err));
});

The error I am getting is

{“headers”:{“normalizedNames”:{},“lazyUpdate”:null,“headers”:{}},“status”:0,“statusText”:“Unknown
Error”,“url”:null,“ok”:false,“name”:“HttpErrorResponse”,“message”:“Http failure response for (unknown url):
0 Unknown Error”,“error”:{“isTrusted”:true}}

I think it is because of CORS, so I set up my web server to accept CORS. And it is working on ios/browser. However, it is still getting this error on Android. Also, my web server didn’t receive any requests from Android (not even the OPTIONS request).

Any suggestion is appreciated!


#2

I would not describe this as anywhere close to “standard”. Follow the idioms in part 6 of the Tour of Heroes instead.

Do not:

  • explicitly instantiate a Promise
  • stringify the payload
  • create custom headers
  • set content type
  • subscribe in the same place you generate the Observable, but rather return it instead
  • use localhost, because it won’t work on device

Do:

  • use HTTPS instead of naked HTTP
  • use a host name instead of localhost
  • get an SSL certificate
  • work with the Observables that HttpClient gives you

#3

Thanks for the advice! It turned out that android cannot use localhost, but ios can.

For localhost vs host name, localhost does make development easier though.