【发布时间】: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选项。那可能应该是POST和body? -
它在 fetch 调用参数中: JSON.stringify({ device_latitude: deviceLat, device_longitude: deviceLong }) 它应该只是一个get请求。
-
我了解到您已将
params放入选项中,但fetchAPI 并没有说params是一个有效选项,这意味着它被忽略了。 -
你知道如何使它成为一个有效的选项吗?
-
Postman 使用的网址是什么?
标签: react-native redux es6-promise fetch-api reducers