我在coursera上开始了一个原生脚本课程。当我想要发送一个http请求到我的json-server时,我在我的android手机上得到了以下错误:错误0:未知错误http失败响应..
export const baseURL="http://10.0.2.2:3000/";我的餐具服务:
@Injectable({
providedIn: 'root'
})
export class DishService {
constructor(private http: HttpClient,
private processHTTPMsgService: ProcessHTTPMsgService) { }
getDishes(): Observable<Dish[]> {
return this.http.get<Dish[]>(baseURL + 'dishes')
.pipe(catchError(this.processHTTPMsgService.handleError));
}
getDish(id: string): Observable<Dish> {
return this.http.get<Dish>(baseURL + 'dishes/' + id)
.pipe(catchError(this.processHTTPMsgService.handleError));
}
getFeaturedDish(): Observable<Dish> {
return this.http.get<Dish[]>(baseURL + 'dishes?featured=true').pipe(map(dishes => dishes[0]))
.pipe(catchError(this.processHTTPMsgService.handleError));
}消息服务:
export class ProcessHTTPMsgService {
constructor() { }
public handleError(error: HttpErrorResponse | any) {
let errMsg: string;
if (error.error instanceof HttpErrorResponse) {
errMsg = error.error.message;
} else {
errMsg = `${error.status} - ${error.statusText || ''} ${error.message}`;
}
return throwError(errMsg);
}
}菜单组件:
export class MenuComponent implements OnInit {
dishes: Dish[];
errMess: string;
constructor(private dishService: DishService,
@Inject('baseURL') private baseURL) { }
ngOnInit() {
this.dishService.getDishes()
.subscribe(dishes => this.dishes = dishes,
errmess => this.errMess = <any>errmess);
}菜单组件html:
<ActionBar title="Menu" class="action-bar">
</ActionBar>
<StackLayout class="page">
<ListView [items]="dishes" class="list-group" *ngIf="dishes">
<ng-template let-dish="item">
<StackLayout orientation="horizontal" class="list-group-item">
<Image row="0" col="0" rowSpan="2" height="108" width="108" [src]="baseURL + dish.image" class="thumb p-16"></Image>
<GridLayout class="list-group-item" rows="auto *" columns="*">
<Label row="0" col="0" [text]="dish.name" class="list-group-item-heading"></Label>
<Label row="1" col="0" class="list-group-item-text" [text]="dish.description"></Label>
</GridLayout>
</StackLayout>
</ng-template>
</ListView>
<ActivityIndicator busy="true" *ngIf="!(dishes || errMess)" width="50" height="50" class="activity-indicator"></ActivityIndicator>
<Label *ngIf="errMess" [text]="'Error: ' + errMess"></Label>
</StackLayout>我也尝试了"http://127.0.0.1:3000/“,但我得到了同样的错误,我还在应用程序部分的androidmanifest.xml中添加了android:usesCleartextTraffic="true”。有人能帮帮忙吗?我快被吓到了
发布于 2020-07-23 20:48:38
也许可以尝试显示整个错误以获取更多信息。
errMsg = error.error
并查看控制台,看看是否有其他错误
发布于 2020-07-28 03:10:39
我在上面的代码中没有看到任何问题。
听起来您很难连接到您的json服务器。
您是否验证了您的服务器正在相同的up和端点上发送响应?(使用邮递员或类似的工具)。
服务器是否也在监听ip,还是只监听本地主机?如果您正在使用npm包json-server,那么这可能是有用的json-server cannot access via local IP
您是使用模拟器还是在您的设备上进行测试?我要做的下一步是验证您可以使用rest客户端应用程序连接到服务器。在这种情况下,127.0.0.1或localhost指的是电话,而不是计算机。
https://stackoverflow.com/questions/63053784
复制相似问题