【问题标题】:Nativescript localhost http call fails on iOSiOS 上的 Nativescript localhost http 调用失败
【发布时间】:2019-10-16 14:27:58
【问题描述】:

我在 Windows 上使用 Nativescript sidekick cloud build 在 iOS 上测试我的应用 - 我还连接了我的 iPhone。

根据this 的帖子,我正在向 localhost 发送我的 http 请求,但他们一直因为这个错误而失败。

http://localhost:52553/api/rewards/all 的 Http 失败响应:0 未知错误
错误:无法连接到服务器。

这是我的奖励服务实现

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";

import { Observable, of } from 'rxjs';
import { SimpleReward } from "../models/simple-reward";
import { take, catchError } from "rxjs/operators";

@Injectable()
export class RewardsService {

    private baseUrl = "http://localhost:52553/api/rewards";

    constructor(private http: HttpClient) { }

    getAllRewards(): Observable<SimpleReward[]> {
        const url = `${this.baseUrl}/all`;
        return this.http.get<SimpleReward[]>(url).pipe(
            catchError((e) => {
                console.error(e);
                return of([]);
            })
        );
    }
}

请指导我在这里做错了什么?

【问题讨论】:

  • 将 NSAppTransportSecurity 添加为默认情况下 ios 中不允许使用非 https

标签: angular nativescript


【解决方案1】:

localhost 添加为app/App_Resources/iOS/Info.plist 文件的例外,以允许与http://localhost 域进行不安全(非HTTPS)通信:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

这比允许与所有域的不安全通信更可取。

编辑:另外,请记住,您必须在编辑 Info.plist 文件后重新构建您的应用程序!它的变化不能像 JS 那样简单地实时同步或重新加载热模块。

【讨论】:

  • 感谢您的回复。我添加了它,但得到了同样的错误。
  • @shobhitvaish 您需要在更改 Info.plist 后重新构建应用程序;是你做的吗?可以进行干净的构建以避免怀疑。
  • 我尝试了干净的构建,但没有运气。我确定我的本地主机正在工作
  • 等一下。你在桌面上运行localhost,不是吗?尝试在您的模拟器而不是物理设备上运行该应用程序:tns run ios --emulator。您的 iPhone 将无法访问您的桌面 Web 服务器的 localhost。如果你想从你的物理 iPhone 连接到它,你需要在你的桌面上打开网络共享(可能还禁用防火墙端口)并从你的 iPhone 连接到特定的 IP 而不是 localhost 并提供相应的NSExceptionDomains 条目。
  • 所以我终于让它工作了。感谢您的指导!
【解决方案2】:

您可以在 info.plist 中禁用安全性或将 localhost 添加为例外。

<key>NSAppTransportSecurity</key>  
 <dict>  
      <key>NSAllowsArbitraryLoads</key><true/>  
 </dict>

【讨论】:

  • 试过了 - 没有运气:(
猜你喜欢
  • 2019-02-25
  • 1970-01-01
  • 2019-08-04
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多