为什么fetch返回一个奇怪的整数哈希? [英] Why does fetch return a weird hash of integers?
问题描述
我正在使用带有React Native的 fetch
API。
I'm using fetch
API with React Native.
我的回复遵循正常格式 {message:error here}
如果状态> = 400,我将在原生弹出窗口中显示。
My response follows a normal format of {"message": "error here"}
if the status is >= 400, which I will show in a native popup.
我正在尝试在检测到故障后调用 response.json()
,但它仍然以一种奇怪的格式放置所有内容......
I'm trying to call response.json()
after detecting a failure, but it keeps putting everything in a weird format...
{_45:0,_81:0,_65:null,_54:null}
无论出于何种原因...我想要的实际响应位于 _65
...我不知道这些随机密钥是什么。
For whatever reason... the actual response I want is located in _65
... I have no idea what these random keys are.
所以目前我不得不通过 _bodyText
访问它,但我认为这是错误的,因为它是一个私有的下划线方法。
So currently I'm having to access it via _bodyText
, but I assume that is wrong because it's a private underscore method.
我做错了什么?
var API = (function() {
var base = 'https://example.com/api/v1';
var defaults = {
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
};
var alertFailure = function(response) {
if (response.status >= 200 && response.status < 400) {
return response;
} else {
var json = JSON.parse(response._bodyText || '{}');
var message = json.message || 'There was a problem. Close the app, and try again later.';
var error = new Error(message);
error.response = response;
throw error;
}
};
var callAPI = function(url, opts) {
opts.headers['X-Version'] = 'v' + Package.version;
return fetch(base + url, opts)
.then(alertFailure)
.then((response) => {
return response.json();
})
.catch((error) => {
Alert.alert(null, error.message);
});
};
return {
get: function(url, opts) {
var fullOpts = Object.assign({}, defaults, opts);
return callAPI(url, fullOpts);
},
post: function(url, data, opts) {
var fullOpts = Object.assign({}, defaults, {
method: 'POST',
body: JSON.stringify(data || {})
}, opts);
return callAPI(url, fullOpts);
}
};
})();
推荐答案
答案是。 json()
返回一个承诺...所以我必须在 .then()
The answer is that .json()
returns a promise... so I had to do everything from within .then()
这篇关于为什么fetch返回一个奇怪的整数哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!