status: -1: There was an error with the request: no protocol:

695 Views Asked by At

I'm trying to do an HTTP request on an android emulator, I built with ionic and compiled with capacitor.

I'm using the HTTP module from @ionic-native/http/ngx. I have a per-existing interceptor that I used when I was making requests using the HttpClient from @angular/common/http. This is what that interceptor looks like:

export class InterceptorService implements HttpInterceptor {
  protected apiUri = environment.API_URL;
  constructor(
      private authSvc: AuthService,
      private toastCtrl: ToastController
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const url = this.apiUri + req.url;
    const token = this.authSvc.getStorageToken();
    if (token) {
      req = req.clone({
        url,
        headers: req.headers.set('Authorization', `Bearer ${token}`)
      });
    }
    return next.handle(req).pipe(
        map((event: HttpEvent<any>) => {
          return event;
        }),
        catchError( (err: HttpErrorResponse) => {
          let errMessage =  err.error.message;
          if (err.error.title) {
            errMessage = err.error.title;
          }
          if (!errMessage) {
            errMessage = err.error;
          }
          this.presentToast(err.status, errMessage);
          return throwError(err);
        })
    );
  }
  async presentToast(status: number, message: string) {
    const toast = await this.toastCtrl.create({
      message,
      buttons: ['OK']
    });
    await toast.present();
  }
}

My auth-service:

   /* service request to get a toke */
    getAuthToken(model: IGetTokenModel) {
        return this.http.post('/user/token', model, {});
      }

The environment.API_URL is the url to my API on my local machine.

I'm guessing the no protocol means I'm posting data to /user/auth instead of the full which includes the hostname. But I'm not sure of this. However, if that were the case, how would I refactor my interceptor so that it works as expected with the @ionic-native/http/ngx?

1

There are 1 best solutions below

0
On

Finally have this sorted. I was pointing to localhost inside the emulator. Turns out that requests made inside the emulator have to point to http://10.0.2.2:PORT.

I suppose localhost in a sense still point to the emulator itself.