【问题标题】:How can I get the nested elements of JSON array from fetch API?如何从 fetch API 获取 JSON 数组的嵌套元素?
【发布时间】:2019-04-06 00:51:41
【问题描述】:

我正在尝试使用 React Native 中的 fetch api 从服务器获取一些数据。如何以 JSON 格式获取所有字段,包括嵌套字段?

我已经尝试在从 Promise 中获取数据后转换为 JSON。但是,数据格式不正确。使用邮递员获取相同的数据会为我提供填充的所有数据和字段。

我的 fetch api 如下所示:

fetch("https://someurl.com/apps/api/", {
    method: "GET",
    headers: {
      api_key: "somekey",
      "Content-Type": "application/json"
    },
    params: JSON.stringify({
      device_latitude: deviceLat,
      device_longitude: deviceLong
    })
  })
    .then(response => response.json())
    .then(restData => {
      dispatch({
        type: FETCH_REST,
        payload: restData
      });
    })
    .catch(error => {
      console.error(error);
    });

这是我在reducer 中对restData 进行控制台登录时来自fetch api 的响应数据:

[  
   Object {  
      "restID":1,
      "name":"Rest1",
      "restLocation": null
   },
  Object {  
      "restID":2,
      "name":"Rest2",
      "restLocation": null
   }
]

以下是我使用 Postman 调用端点时的结果。

注意:下面的 restLocation 字段有更多的数据,在使用上面的 fetch api 时不存在:

[  
   {  
      "restID":1,
      "name":"Rest1",
      "restLocation":{  
         "id":2,
         "distance":2
      }
   },
   {  
      "restID":2,
      "name":"Rest2",
      "restLocation":{  
         "id":3,
         "distance":1
      }
   }
]

【问题讨论】:

  • 我在the parameters 中没有看到任何params 选项。那可能应该是POSTbody
  • 它在 fetch 调用参数中: JSON.stringify({ device_latitude: deviceLat, device_longitude: deviceLong }) 它应该只是一个get请求。
  • 我了解到您已将params 放入选项中,但fetch API 并没有说params 是一个有效选项,这意味着它被忽略了。
  • 你知道如何使它成为一个有效的选项吗?
  • Postman 使用的网址是什么?

标签: react-native redux es6-promise fetch-api reducers


【解决方案1】:

GET参数应该是url编码后放入fetchurl中。

例如GET /test 与邮递员PARAMS foo1=bar1foo2=bar2 应向GET 发送GET 请求。

我们可以将您的参数{device_latitude: deviceLat, device_longitude: deviceLong} 编码如下:

const url = `https://someurl.com/apps/api/?device_latitude=${deviceLat}&device_longitude=${deviceLong}`;
const fetchableUrl = encodeURI(url);

然后fetch 以同样的方式删除params,因为它们属于网址:

fetch(fetchableUrl, {
    method: "GET",
    headers: {
      api_key: "somekey",
      "Content-Type": "application/json"
    }
})
.then(response => response.json())
.then(restData => {
    dispatch({
        type: FETCH_REST,
        payload: restData
    });
})
.catch(error => {
    console.error(error);
});

【讨论】:

  • 现在完美运行。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 2020-03-21
相关资源
最近更新 更多