【问题标题】:Fetch Api:Can not get data from localhostFetch Api:无法从本地主机获取数据
【发布时间】:2017-02-18 07:17:22
【问题描述】:

我一直在尝试使用 nativescript 创建一个 android 应用程序。我正在使用 fetch 模块从我的服务器获取响应。当我试图从 httpbin.org/get 获取响应时,它是好的。但是当我尝试从本地服务器获取响应时,我收到 Network Request Failed. 错误。

发送到httpbin.org/get-

return fetchModule.fetch("https://httpbin.org/get").then(response => { return response.text(); }).then(function (r) {
        console.log(r);
    }, function (e) {
            console.log(e);
        }); 

发送到 localhost:8000/api-

return fetchModule.fetch("http://localhost:8000/api").then(response => { return response.text(); }).then(function (r) {

       console.log(r);

}, function (e) {

        console.log(e);
    });

当我尝试通过 request 模块从纯 node.js 中的 localhost:8000/api 获取响应时,它工作正常。但是现在,我不知道如何在 nativescript 中使用 fetch 模块解决这个问题。

【问题讨论】:

  • 你确定你的手机有网络连接吗?
  • 不要使用 localhost 作为 localhost 指向本地设备,在这种情况下您的手机不是服务器。检查你的电脑什么是 IP 并更改 localhost 的 IP
  • 为什么要联网?我正在使用 Android Studio 的 AVD。
  • 查看这个答案stackoverflow.com/q/5806220/3284355 localhost 指的是设备(模拟器)而不是模拟器运行的计算机的IP。

标签: android node.js laravel-5.2 nativescript fetch-api


【解决方案1】:

模拟器 API 路径:- http://10.0.2.2:5000。就像您的 API 本地路径是 http://198.168.1:5000/api 或 http://localhost:5000/api 然后替换为 http://10.0.2.2:5000/api 并且端口地址与您的本地 API 端口相同。

路径- App_resources/Android/src/main/AndroidManifest.xml :-

android:usesCleartextTraffic="true" 添加应用标签

【讨论】:

    【解决方案2】:

    相反,localhost(通常是 127.0.0.1)使用 10.0.2.2(如果使用 AVD 模拟器)

    10.0.2.2  - Special alias to your host loopback interface 
    (i.e., 127.0.0.1 on your development machine)
    

    对于 GenyMotion 模拟器,环回地址是 10.0.3.2

    【讨论】:

    • 像这样 - 10.0.2.2/api 还是像这样的 10.0.2.2:8000/api?
    • @user145959 你应该使用https://10.0.2.2 instaed http://localhost ... IP地址192.168.xx(表示本地网络中的地址)与环回地址无关所以我不是确定你为什么首先尝试使用它。
    • @NickIliev:我像这样 export const baseURL = "https://10.0.2.2:3000"; 更改了我的代码,但没有用。我更新了我的问题
    猜你喜欢
    • 1970-01-01
    • 2014-04-02
    • 2019-07-25
    • 1970-01-01
    • 2017-07-12
    • 2017-09-15
    • 2019-11-03
    • 2022-08-23
    • 2018-07-20
    相关资源
    最近更新 更多