我试图在React Native中使用fetch api从服务器获取一些数据。如何以JSON格式获取它,所有字段显示包括嵌套的?
我从承诺中获取数据后已经尝试过转换为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
}
}
]
GET
参数应该是url编码并放入fetch
网址。
例如GET /test
与邮递员PARAMS
foo1=bar1
和foo2=bar2
应该向GET
发送/test?foo1=bar1&foo2=bar2
请求。
我们可以编码你的params {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
因为它们属于url:
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);
});