I am using the fetch API with React Native.
My answer follows the normal format {"message": "error here"} if status => 400, which I will show in my own popup.
I try to call response.json() after a failure is detected, but it keeps everything in a weird format ...
{ _45: 0, _81: 0, _65: null, _54: null }
For some reason ... the actual answer I want is in _65 ... I don't know what these random keys are.
Therefore, currently I need to access it through _bodyText , but I assume this is wrong, because it is a private underscore method.
What am I doing wrong?
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); } }; })();