【问题标题】:I can't access to data in JSON.server from react-native with use of Fetch's method我无法使用 Fetch 的方法从 react-native 访问 JSON.server 中的数据
【发布时间】:2019-12-09 18:41:39
【问题描述】:

我使用以下代码创建了一个简单的 JSON.server 项目: npm install JSON-server -g

我使用以下代码运行此服务器: JSON-server --watch db.json -p 3001 -d 2000

当我在浏览器中运行此服务器时,它可以工作,但是当我从该服务器以 react native 获取数据时,这不起作用。

我的 react-native 用于从 JSON.server 获取数据的代码:

return fetch(baseUrl + "data")
  .then(
    response => {
      if (response.ok) {
        return response;
      } else {
        //error
      }
    },
    error => {
      var errmess = new Error(error.message);
      throw errmess;
    }
  )
  .then(response => response.json())
  .then(dishes => dispatch(fetchData(data)))
  .catch(error => dispatch(dataFailed(error.message)));

fetchData方法:

export const fetchData = data => ({
  data: data
});

更新 1:

这是baseUrl:

export const baseUrl = "http://192.168.1.8:3001/";

请帮我看看有什么问题。

I have tried this question but my problem has not fixed.

【问题讨论】:

  • 你遇到了什么错误?
  • 您的端点不应该是fetch(baseUrl + "db.json"),因为您正在观看该文件而不是dishes?您的服务器上db.json 中是否有可用的GET /dishes 路由?如果您可以共享db.json 中定义的错误消息和路由,可能会有所帮助。
  • 您还设置了自定义端口3001,而不是默认的3000。这需要添加到baseUrl 例如:http://localhost:3001/<route>
  • 我已经更新了我的问题。请再看一遍。
  • 我没有任何错误。我没有收到来自 JSON.server 的任何数据。 @Clarity

标签: react-native react-redux


【解决方案1】:

我的问题是因为我的 ip4 地址。
正如我之前所说,I have tried this question but my problem has not fixed.
我确实找到了一种从服务器获取数据的方法。

对于那些面临类似问题的人。

步骤:

1) 转到https://ngrok.com/ 并创建帐户

2) 登录

3) 进入设置和安装,按照 1、2 步骤操作。

4) 将 ngrok.exe 放在您选择的文件夹中。确保该文件夹位于您的 PATH 环境变量中。

5) 按照设置和安装的第 3 步进行操作。

6) 打开命令提示符并输入 ngrok http(例如:3005)并回车。你会得到一个ngrok url(例如:转发http://977ab183.ngrok.io

7) 将此网址(例如:http://977ab183.ngrok.io/)设为您的应用程序 baseUrl

8) 打开另一个指向您的应用目录的命令提示符并运行您的 json 服务器:json-server --watch db.json -p 3005 -d 2000

【讨论】:

    【解决方案2】:

    您可以使用 localtunnel 让服务器在两台设备上都运行:

    在您的开发机器上全局安装 localtunnel

    yarn global add localtunnel
    

    然后你使用 json-server 来设置和运行一个模拟服务器。以下命令在 localhost 和端口 8000 上设置模拟服务器

    json-server --port 8000 ./db.json --watch
    

    接下来使用 localtunnel 将模拟服务器暴露给网络

    lt --port 8000 --subdomain application-mock-server
    

    上述命令将返回一个可通过 Internet 访问的 URL,格式为

     https://application-mock-server.localtunnel.me.
    

    然后,您将这个 URL 插入到您的 React Native 代码库中,并且可以从在移动设备上运行的 Expo 中的应用程序访问。

    * 查看全文here.

    【讨论】:

      猜你喜欢
      • 2018-12-25
      • 2020-06-03
      • 2019-01-15
      • 2020-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多