【发布时间】:2018-01-24 03:46:29
【问题描述】:
我在我的设备上测试我的 ReactNative-App 时遇到了一些奇怪的行为。哪里可以告诉我我做错了什么。
首先我有一个返回帖子列表的 REST-API。这里是邮递员请求的一些输出(它与稍后在应用程序中的 url 相同):
{
"status": 200,
"data": [
{
"id": "6bb373c6dbe8c4782121068223a1d5bf710a14a62943443bdc5c017ce873935a",
"description": "",
"upvotes": 0,
"downvotes": 0,
"creationTime": "2017-08-16T04:44:03Z"
},
{
"id": "5ae791aa33512dc179f075649f68731f269c366a37807f7da9eeeabafcda8c7d",
"description": "",
"upvotes": 0,
"downvotes": 0,
"creationTime": "2017-08-16T04:42:27Z"
},
],
"version": "0.0.1",
"servertime": "2017-08-16T07:02:32.250978864+02:00"
}
我希望通过 wifi 和移动互联网获取此对象。
这里是在我的应用程序中请求我的 API 的代码片段:
exports.getPosts = function() {
return fetch(HTTP.baseurl + "/image", {
method: "GET"
}).then(res => res.json()).then((res)=>{
//this is the line you will see the output from
console.log(JSON.stringify(res, null, 2));
return res
});
}
如果使用 wifi 请求 API,我会得到与邮递员相同的对象。 但如果通过移动互联网请求,我会得到以下对象:
{
"status": 200,
"data": {
"id": "5ae791aa33512dc179f075649f68731f269c366a37807f7da9eeeabafcda8c7d",
"description": "",
"upvotes": 0,
"downvotes": 0,
"creationTime": "2017-08-16T06:42:27.37228137+02:00"
},
"version": "0.0.1",
"servertime": "2017-08-16T06:42:27.4874009+02:00"
}
测试于:
macOS: 10.12.6
XCode: 8.3.3
iOS: 10.3.3 (iPhone 6)
node: 8.4.0
react: 16.0.0-alpha.12
react-native: 0.45.1
编辑:
我还在一个新的 react 原生应用上复制了它,只插入了以下代码行:
//first send an image to the API
fetch("http://services.impressions-app.com/test/image", {
method: "POST",
body: JSON.stringify({"blob": blob, "description": ""})
}).then(res => res.json()).then(res => {
//then request all the images including the new one
return fetch("http://services.impressions-app.com/test/image", {
method: "GET"
})
}).then(res => res.json()).then(res => {
//should log an array of imageobjects (see postman response above)
console.log("LOADED", res);
}).catch(e => {
console.error(e)
});
我得到了一个像上面这样的对象,其中数据作为对象而不是数组:
{
"status": 200,
"data": {
"id": "06c50436c2b2b671a64ce3b57b6cac76b648a83ed621305a0f6a55f8186957ba",
"description": "",
"upvotes": 0,
"downvotes": 0,
"creationTime": "2017-08-17T08:00:24.198626835+02:00"
},
"version": "0.0.1",
"servertime": "2017-08-17T08:00:26.031231455+02:00"
}
测试于:
macOS: 10.12.6
XCode: 8.3.3
iOS: 10.3.3 (iPhone 6)
node: 8.4.0
react: 16.0.0-alpha.12
react-native: 0.45.1
编辑#2:
我查看了日志文件,它只在我通过 wifi 请求时记录了这个请求。其他请求按预期记录。
也许是缓存问题?
你们中有人遇到过类似的问题吗?
非常感谢
【问题讨论】:
-
两个响应的结构不同,在第一个响应中
data属性是一个数组,而在第二个响应中data是一个对象。您确定它们来自同一来源吗? -
我不知道 API,但是后端开发人员有可能将他的应用程序编程为如果只有一个结果则返回一个对象,否则返回数组。
-
@VahidBoreiri 是的,它们肯定来自同一个来源,因为除了 wifi 开关我没有改变任何东西。
-
@Eden 是的,我想到了同样的事情,但是邮递员请求显示了无论有多少对象,API 都应该返回什么
-
你能用邮递员测试这两个网络吗?先用你常用的wifi,再用你的手机热点,再用postman调用API。
标签: node.js rest reactjs react-native fetch-api