我正在尝试使用React Native中的访存api从服务器获取一些数据。如何以JSON格式获取所有显示的字段,包括嵌套字段?
我已经从诺言中获取数据后尝试转换为JSON。但是,数据格式不正确。使用邮递员提取相同的数据会为我提供所有已填充的数据和字段。
我的提取API如下:
<div class="visible">Click to hide</div>
这是我在reducer中的restData上进行控制台日志时从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);
});
以下是我使用邮递员呼叫端点时的结果。
注意:下面的restLocation字段具有更多数据,而使用上述api时,这些数据不存在:
[
Object {
"restID":1,
"name":"Rest1",
"restLocation": null
},
Object {
"restID":2,
"name":"Rest2",
"restLocation": null
}
]
答案 0 :(得分:1)
GET
参数应进行网址编码,并放入fetch
网址中。
例如,带有邮递员GET /test
PARAMS
和foo1=bar1
的{{1}}应该向foo2=bar2
发送GET
请求。
我们可以对您的参数/test?foo1=bar1&foo2=bar2
进行如下编码:
{device_latitude: deviceLat, device_longitude: deviceLong}
然后以相同的方式const url = `https://someurl.com/apps/api/?device_latitude=${deviceLat}&device_longitude=${deviceLong}`;
const fetchableUrl = encodeURI(url);
将其fetch
删除,因为它们属于URL:
params