getting text from react native fetch call - react-native

I'm not able to parse the data from the fetch call
Below is the method
onLoginPress=()=>{
console.log("username="+this.state.username);
console.log("password="+this.state.password);
this.sendLoginRequest(this.state.username,this.state.password)
.then((response) => {
console.log("RESPONSEEEEEEEEEEEEEEEE");
console.log(response.text())
console.log( Promise.resolve(response));
response.json();
})
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
};
The response i get it is a promise and i'm not able to get the token out of it.
Below is the log for response.text()
{
_45: 0, _81: 1,
_65: '"3h8112qe2qobox3675ghmq9dtcbjvddc"',
_54: null }
For console.log( Promise.resolve(response)) the output is
{
_45: 0,
_81: 1,
_65: { type: 'default',
status: 200,
ok: true,
statusText: undefined,
headers: { map: { connection: [ 'Keep-Alive' ],
'content-length': [ '34' ],
'content-type': [ 'application/json; charset=utf-8' ],
'set-cookie': [ 'persistent_shopping_cart=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT; Max-Age=0; path=/' ],
'cache-control': [ 'no-store, no-cache, must-revalidate' ],
expires: [ 'Thu, 19 Nov 1981 08:52:00 GMT' ],
pragma: [ 'no-cache' ],
server: [ 'Apache/2.4.23 (Ubuntu)' ],
'keep-alive': [ 'timeout=5, max=100' ],
[ 'Tue, 20 Jun 2017 06:58:16 GMT' ] } },
url:'http://integration/customer/token',
_bodyInit: '"3h8112qe2qobox3675ghmq9dtcbjvddc"',
_bodyText: '"3h8112qe2qobox3675ghmq9dtcbjvddc"',
bodyUsed: true
},
_54: null }
responseJson returns undefined.
How to get the token(3h8112qe2qobox3675ghmq9dtcbjvddc) out of the data.
Thanks!

It appears that your API is returning text. So you need to call the text() method and return it to chain with a then:
onLoginPress=()=>{
this.sendLoginRequest(this.state.username,this.state.password)
.then((response) => {
return response.text();
})
.then((responseJson) => {
console.log(responseJson);
})
.catch((error) => {
console.error(error);
});
};
If your API returns JSON, you would do exactly the same by swapping the text() call by a json() call. See the React Native fetch doc.

Related

VueJS and Axios handle errors properly

I am trying to raise an error during the login ... but weird thing is -> it does not work as I would expect it to ...
I am having this simple auth.service.js
class AuthService {
async login(params) {
try {
const user = (await axios.post('/authentication', { ...params })).data;
return true;
} catch (err) {
console.log(err);
throw new Error(err);
}
}
}
export default new AuthService();
The "err" has the full axios error object (as shown below)
{
"message": "Request failed with status code 401",
"name": "AxiosError",
"stack": "AxiosError: Request failed with status code 401\n at settle (http://localhost:3000/node_modules/.vite/deps/axios.js?v=430fef65:1124:12)\n at XMLHttpRequest.onloadend (http://localhost:3000/node_modules/.vite/deps/axios.js?v=430fef65:1335:7)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"adapter": [
"xhr",
"http"
],
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"env": {},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
"baseURL": "http://localhost:3030",
"method": "post",
"url": "/authentication",
"data": "{\"username\":\"admin\",\"password\":\"admin\",\"strategy\":\"local\"}"
},
"code": "ERR_BAD_REQUEST",
"status": 401
}
what is weird is, that when I use that in my login method .. I am getting just the name and message values ... nothing else :(
methods: {
async login() {
const payload = { username: this.username, password: this.password, strategy: 'local' };
AuthService.login(payload)
.then(() => {
this.$router.push({ name: 'home' });
this.loading = false;
})
.catch(error => {
console.log(error); // THIS DOES NOT SHOW THE ENTIRE OBJECT WITH ALL KEYS
this.loading = false;
});
},
any idea why?

Status failed error get after enter card input in network international ngenius payment in react native?

First we create sandbox account from https://www.network.ae/en/contents/listing/online-solutions#book-1
then we create access Token see code
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/vnd.ni-identity.v1+json");
myHeaders.append("Authorization", `Basic ${}API_KEY`);
myHeaders.append("Cookie", "\_abck=5C342393A623B53581D9AE558C857BF2\~-1\~YAAQfXYsMa+W3wWFAQAACGk7MwlNL93fTExvJYX4pRpd6PZpRFbRT0BgePfZ2tn15MkLCVst80XVExP/xPZkPh0LUZq4QO4k+KN0bm+Tz0NlX26lWmSlI6mq0kePXMH9MJt7yQy7Rx9ZIsR2Amcb44zP+hnySdCx2uq3vwgl4ZVMQ2soqosGNHQuESjb/JJAirysYwiyN7/Mw/qg5NzXzf2ncRTbB/3CcVp/yiZPOwAsxD8x+8oZA3VAxLgvbuv0Tn9ccNN9oPATqzDtoXD1LnQorof6S/S6btPx4BZTgFeqvmxX3q5SNSlsDgySTzI5qkp81wrjTm5ficp1U0k5fcimfaR0V8Xq21luPY9VdveWYd5B87UOIcalA2CQz2S7yFSo14uqKarLVFbh00Vd1Zw=\~-1\~-1\~-1; bm_sz=AF5FEAEE5BC3A58968E80BB8D640735E\~YAAQfXYsMbCW3wWFAQAACGk7MxLpffLMR5ZpUagjSJqRS4G5rjc8MolC2xNhZUaUKTKGMj5Fvi0eLn3cbULd/jtI4QO0h8Cl4c3bFROSPs9jpPu1UFDm9R1gGBB6T7rIFPU+sxiw2wQ7gGvrlik680yFDoUraO3MoRl8cfpOu73nyKryhpb1ebghFcrF2aYM9B4f3c8ER1Fk1VTXN5TGij9bLAT7BDjVOtLjQVG5AL/wKZ57t21EFnCqlnXioDXla8Jylj6T7EQzE/5yKno2Z9Z6jMTx1rU6Jcy5nUq6SG50aVYOUYwA/w1k6WSj\~3749186\~4343095");
var raw = "";
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://api-gateway.sandbox.ngenius-payments.com/identity/auth/access-token", requestOptions)
.then(response => response.json())
.then(result => {
setAccessToken(result.access_token)
})
.catch((e)=>console.log(e)
Then we create an order
var myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${access_token}`);
myHeaders.append("Content-Type", "application/vnd.ni-payment.v2+json");
myHeaders.append("Accept", "application/vnd.ni-payment.v2+json");
myHeaders.append("Cookie", "_abck=5C342393A623B53581D9AE558C857BF2~-1~YAAQJfhWuMbikwmFAQAAm3R2KgkBO6swEeKoHNG6113OL/hvGd9LQQEo5ieCnty0rrZ7UcaRqt7InR2UUWFze7723wDPiy+SCmtMNKKL4zCJi7fwqJed1SMa2PWjCe5qWiFf/Fa0NtMY3a7TedM+6XI3cMMieW4GMHrQwGTz0BrFsZ3gC6jCUgYUTFO55uMpD3627GjbcZmsluCPLWKVLdGlsPX/wIknh1Tl/+YSO58Bnv97KpZnb0ZLZck2PYFnzGOPTiJ2JQe6vakvSFh68UxMIZYVxekwS2LTZjJGtZqLMt45A/lLbpxq95qzzCMWdxrwE0JgMgWfgu9l1k+Scq69UpgOo331AEJ+AASZF1MZ4CRJ7MEs1WpjlTbDroZVS0Uh~-1~-1~-1");
var raw = JSON.stringify({
"action": "PURCHASE",
"amount": {
"currencyCode": "AED",
"value": 2000
},
"emailAddress": "govindsingh#gmail.com",
"merchantOrderReference":"my-order",
"billingAddress":{
"firstName":"Govind",
"lastName":"Singh",
"address1":"abc",
"city":"Dubai",
"state":"Dubai",
"countryCode":"AED"
},
"merchantAttributes":{
"skipConfirmationPage":true,
"skip3DS":true
}
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch(`https://api-gateway.sandbox.ngenius-payments.com/transactions/outlets/${Outlet_id}/orders`, requestOptions)
.then(response => response.json())
.then(result => {
setOrder(result.access_token)
})
.catch((e)=>console.log(e)
then we call make card payment function by https://www.npmjs.com/package/#network-international/react-native-ngenius
const res = await initiateCardPayment(order);
console.log("res"+ res)
Alert.alert(
'Success',
'Payment was successful',
[{ text: 'OK', onPress: () => console.log('OK Pressed') }],
{ cancelable: false },
);
} catch (err) {
console.log(err);
alert(
'Error',
'Payment was not successful',
[{ text: 'OK', onPress: () => console.log('OK Pressed') }],
{ cancelable: false },
);
}
then we get an error -
[status:failed]
Thanks in Advance
Please give me any solution

Simple axios call using wait and async works but when i put in in redux-thunk. it start giving errors in react native

import axios from 'axios'
export const loadData = (basicAuth, URL) => {
return (dispatch, getState) => {
dispatch({ type: 'LOGIN_START' })
axios.post(
URL,
null,
{ params: { 'email': 'zack', 'password': 'zack' } },
{
headers: {
"Content-Type":
"application/x-www-form-urlencoded; charset=UTF-8",
'Accept': "*/*",
'authorization': basicAuth,
"Access-Control-Allow-Credentials": true,
},
}
).then(function (response) {
dispatch({ type: 'LOGIN_SUCCESS', payload: response })
}).catch(function (error) {
dispatch({ type: 'LOGIN_FAILURE', payload: error })
})
}
}
When call this request in the main thread using wait and async it works but when i call it using this reduc-thunk it start giving errors.
{"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0, "_aborted": false,
"_cachedResponse": undefined, "_hasError": true, "_headers": {"accept": "application/json,
text/plain, /", "content-type": "application/x-www-form-urlencoded"}, "_incrementalEvents":
false, "_lowerCaseResponseHeaders": {}, "_method": "POST", "_perfKey":
"network_XMLHttpRequest_Basic emFjazp6YWNr?email=zack&password=zack", "_performanceLogger":
{"_closed": false, "_extras": {}, "_pointExtras": {}, "_points": {"initializeCore_end":
1659600973109, "initializeCore_start": 1659600972966}, "_timespans":
{"network_XMLHttpRequest_Basic emFjazp6YWNr?email=zack&password=zack": [Object],
"network_XMLHttpRequest_http://10.0.2.2:8081/logs": [Object]}}, "_requestId": null,
"_response": "Expected URL scheme 'http' or 'https' but no colon was found", "_responseType":
"", "_sent": true, "_subscriptions": [], "_timedOut": false, "_trackingName": "unknown",
"_url": "Basic emFjazp6YWNr?email=zack&password=zack", "data": undefined, "readyState": 4,
"responseHeaders": undefined, "status": 0, "timeout": 0, "upload": {}, "withCredentials":
true}

React Native fetch() not outputting body in console log

I am using fetch() to get some data from an API. When testing in Postman the data is returned successfully as JSON. However, when testing from react native app on android I get a text/html response, not sure why. How can I view the body of the response from the text in console.log() to debug? When I do console.log(resp) I can not see the body.
const response = await fetch('https://web.com/api/usersignup', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(resp => {
this.setState({spinner: false});
console.log(resp);// output in console is pasted under this code
return resp.text();
//return resp.json();
})
.then((responseJson) => {
console.log(responseJson);
})
.catch(error => {
this.setState({spinner: false});
Alert.alert('Error', error.message);
throw error;
});
Output I get in Metro Builder when using console.log(). Does not include body.
Response {
"_bodyBlob": Blob {
"_data": Object {
"blobId": "63acc7d8-bd8a-4dd7-b33b-f0e4f202f97e",
"offset": 0,
"size": 0,
},
},
"_bodyInit": Blob {
"_data": Object {
"blobId": "63acc7d8-bd8a-4dd7-b33b-f0e4f202f97e",
"offset": 0,
"size": 0,
},
},
"headers": Headers {
"map": Object {
"cache-control": "public, max-age=0",
"connection": "keep-alive",
"content-length": "0",
"content-type": "text/html; charset=UTF-8",
"date": "Sat, 09 Nov 2019 21:06:05 GMT",
"server": "Apache",
"x-ratelimit-limit": "60",
"x-ratelimit-remaining": "59",
},
},
"ok": true,
"status": 200,
"statusText": undefined,
"type": "default",
"url": "https://web.com/api/usersignup",
}
You cannot print the body until the promise of first then is finished.
I made an example with your code: https://snack.expo.io/#egizas/fetch-print-body
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//body: JSON.stringify(formData)
})
.then(resp => {
console.log('Printing out not json');
console.log(resp);
return resp.json();
})
.then((responseJson) => {
console.log('Printing out json');
console.log(responseJson);
})
.catch(error => {
this.setState({spinner: false});
Alert.alert('Error', error.message);
throw error;
});
Just replace the endpoint and provide correct header.

POST request body with filters in react native

I want to add filters in my request so that I only get my datas when the filter is true.
Unfortunatly, my code doesn't run and I don't know why
mySuperFunction() {
fetch('myhttps', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: {
bool: {
filter: [{ term: { mySuperTerm: true } }],
},
},
size: 1000,
}),
})
.then(response => response.json())
.then(json => {
if (json.found) {
console.log(JSON.stringify(json, null, 4));
}
else {
console.log('error');}
})
What I want to extract is all datas when my filter = true:
"data": {
"name": "eddy",
"city": "london",
"mySuperTerm": true,
}
Do you mean you get no error back at all? Nothing happening?
Wrap Accept in single quotes.
Sorry, it seems to be a bug from react native
See this github issue