1

我是离子新手,如果我的问题很愚蠢,请原谅我。在开发过程中,我使用浏览器显示和测试我的应用程序,它一切正常运行,没有任何问题,但是当我在我的 android 设备上的 Ionic DevApp 上测试我的应用程序时,应用程序无法与后端通信( REST API)。每次我发送一个请求(例如登录请求),系统都会响应[object progressevent]

console.log 显示错误信息:

[ng] [console.log]: {
[ng]   "headers": {
[ng]     "normalizedNames": {},
[ng]     "lazyUpdate": null,
[ng]     "headers": {}
[ng]   },
[ng]   "status": 0,
[ng]   "statusText": "Unknown Error",
[ng]   "url": "http://localhost:8080/restapi/api/user/login",
[ng]   "ok": false,
[ng]   "name": "HttpErrorResponse",
[ng]   "message": "Http failure response for http://localhost:8080/restapi/api/user/login: 0 Unknown Error",
[ng]   "error": {
[ng]     "isTrusted": true
[ng]   }
[ng] }

我的应用程序:

前端:离子+角度

后端(REST API): Java Spring MVC、Oracle Developer Database、Hibernate

我已经搜索并尝试在不同的在线资源上找到解决方案,但不幸的是,其他人提供的解决方案在我的场景中不起作用。因此,我发布这个问题是为了寻求任何离子专家的帮助。谢谢你。

我的登录请求代码:

this.http.login(this.user)
        .subscribe((userData: any) => {
                console.log('Success login');
                this.http.storeToken(userData.token);
                this.loginForm.reset();
                this.errorMessageService.setValidationErrorMessage('');
                this.exceptionHandlerService.setErrorResponse('');
                console.log(userData);
                this.router.navigate(['']);
            },
            error => {
                if (this.exceptionHandlerService.getErrorResponse() === null || this.exceptionHandlerService.getErrorResponse() === '') {
                    console.log(error);
                    this.exceptionHandlerService.setErrorResponse(error.error);
                }
                console.log(error);
            });

我的登录服务代码:

userUrl = 'http://localhost:8080/restapi/api/user/';
login(user: User) {
        const body = JSON.stringify(user);
        return this.http.post<User>(this.userUrl + 'login', body, httpOptions);
    }
4

1 回答 1

3

感谢您的帮助,我已经找到了解决方案。

我将前端应用程序代码中的 API 服务 URL 从 localhost 更改为我的计算机 IP 地址,现在一切正常。

从:

userUrl = 'http://localhost:8080/restapi/api/user/';

到:

userUrl = 'http://192.164.0.111:8080/restapi/api/user/';

对 Reaz Murshed 贡献的答案大喊大叫: 无法从 Android 应用程序连接到 localhost API

于 2019-11-05T14:28:09.013 回答