React Native fetch() not outputting body in console log - react-native

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.

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?

How i can store an API body response and use it in other test on cypress?

I have this code to store response.body.address_id and use it in the next test but not working.
this is my hole code (two tests) :
`it('Create Address',function(){
return cy.request({
method:'POST',
url: `${Cypress.env('API_URL')}/address/api/v1/addresses`,
headers:{
Authorization : `${Cypress.env('access_token')}`,
"Content-Type": 'application/json',
},
body:{
"address_name": "Home",
"locality_area_street": "16th district",
"city": "DAKAR",
"country": "SENEGAL",
}}
).then((response)=>{
expect(response.status).to.eq(201)
Cypress.env('address_id', response.body.address_id);
})
})
it('Add Address',function(){
cy.request({
method:'PUT',
url: 'https://api/v1/cart/address',
headers:{
Authorization : `Bearer ${Cypress.env('access_token')}`,
"Content-Type": 'application/json',
},
body:{
"addressType": "BILLING",
"id": `${Cypress.env('address_id')}`
}}
).then((response)=>{
cy.log(Cypress.env('address_id'));
expect(response.status).to.eq(200)
})
})
})`
Can somme one help me to find a solution ?
You probably shouldn't use the Cypress.env for this,
Try this:
it("Create Address", function () {
return cy
.request({
method: "POST",
url: `${Cypress.env("API_URL")}/address/api/v1/addresses`,
headers: {
Authorization: `${Cypress.env("access_token")}`,
"Content-Type": "application/json",
},
body: {
address_name: "Home",
locality_area_street: "16th district",
city: "DAKAR",
country: "SENEGAL",
},
})
.then((response) => {
expect(response.status).to.eq(201);
Cypress.env("address_id", response.body.address_id);
this.address_id = response.body.address_id;
});
});
it("Add Address", function () {
cy.request({
method: "PUT",
url: "https://api/v1/cart/address",
headers: {
Authorization: `Bearer ${Cypress.env("access_token")}`,
"Content-Type": "application/json",
},
body: {
addressType: "BILLING",
id: this.address_id,
},
}).then((response) => {
cy.log(this.address_id);
expect(response.status).to.eq(200);
});
});

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}

protractor GET and PUT API call

I want to do API call in my protractor test case inside beforeAll() function and once I get the promise return my Test cases should start running. as my test cases are heavily dependent on API response.
I tried using jQuery however it is showing 'jQuery is undefined.' I am using protractor5.3.0.
var data ={
"request": {
"urlPattern": "/portal/user/profile",
"method": "GET",
"headers": {
"Accept": {
"contains": "application/json"
},
"Content-Type": {
"contains": "application/json"
}
}
},
"response": {
"bodyFileName": "abc.json",
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Headers": "Content-Type",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "{{request.headers.Origin}}"
},
"transformers": [
"response-template"
]
}
};
function setUserProfile(profile, data){
var id;
if(data) {
data.response.bodyFileName = "abc.json";
}
jQuery.ajax({
url: "someurl",
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function(result) {
result.mappings.forEach(function(mappingItem) {
if(mappingItem.request.urlPattern === '/portal/user/profile') {
id = mappingItem.id;
}
});
jQuery.ajax({
url: "someurl",
type: 'PUT',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
success: function(result) {
console.log("success?", result);
}
});
}
});
}
describe('Logout Page', function () {
var userDropdownEle;
beforeAll(function () {
request('someurl', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
userDropdownEle = element(by.css(logoutSelectors.dropDownButton));
xchangePageObject.getLoginUrl();
});
});

getting text from react native fetch call

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.