首页 > 解决方案 > 状态:-1:请求出错:无协议:

问题描述

我正在尝试在 android 模拟器上发出 HTTP 请求,我用 ionic 构建并用电容器编译。

我正在使用HTTP来自@ionic-native/http/ngx. 我在使用HttpClientfrom发出请求时使用了一个现有的拦截器@angular/common/http。这就是拦截器的样子:

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();
  }
}

我的身份验证服务:

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

environment.API_URL是我本地机器上我的 API 的 url。

我猜测no protocol我将数据发布到/user/auth而不是包含主机名的完整数据的方式。但我不确定这一点。但是,如果是这种情况,我将如何重构我的拦截器以使其与@ionic-native/http/ngx?

标签: androidangularionic-frameworkcapacitor

解决方案


终于把这个整理好了。我指向模拟器内的本地主机。事实证明,在模拟器内部发出的请求必须指向http://10.0.2.2:PORT.

我想localhost在某种意义上仍然指向模拟器本身。


推荐阅读