android - 状态:-1:请求出错:无协议:
问题描述
我正在尝试在 android 模拟器上发出 HTTP 请求,我用 ionic 构建并用电容器编译。
我正在使用HTTP
来自@ionic-native/http/ngx
. 我在使用HttpClient
from发出请求时使用了一个现有的拦截器@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
?
解决方案
终于把这个整理好了。我指向模拟器内的本地主机。事实证明,在模拟器内部发出的请求必须指向http://10.0.2.2:PORT
.
我想localhost
在某种意义上仍然指向模拟器本身。
推荐阅读
- angular - css 类的 Angular HostBinding 测试
- android - 下载图片后替换我的画廊
- reactjs - 在具有键的元素上反应唯一键错误
- angular - 角度路由下载文件而不是解析组件
- javascript - RegExp 查找和替换两个单独分隔符之间的所有空格
- spring-webflow-2 - 更改流组装的类加载器
- file-upload - ZenCart 文件上传问题
- javascript - 切换更改的按钮类
- python - 如何减小此图中图例的大小?
- android - Java android google maps 显示所有标记和 InfoWindows