Problem with a 'double fetch' call in React Native - javascript

I am having problems using 'nested' Fetch calls within a React Native function. It seems the first Fetch works correctly, however an error is thrown on the second. Here is the code:
//****CALL TWO FETCH REQUESTS...
const data = { passkey: '12345', callup: 'name' };
const secondary = { passkey: '12345', callup: 'name' };
fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(function(response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(data => {
// Store the post data to a variable
_post = data;
console.log('Success on FIRST FETCH:', data);
console.log('answer is:', data.answer);
console.log('answer is:', _post.answer);
// Fetch another API
fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})
})
.then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
})
.then(function (userData) {
console.log('Returned from BOTH fetch calls'); //does not write to console
console.log(_post, userData); //does not write to console
this.vb.start();
})
.catch((error) => {
console.error('Error in onPressPublishBtn:', error);
});
//****
It seems the second Fetch call returns 'undefined', despite being identical to the first Fetch call which seems to work successfully. The error returned is "TypeError: undefined is not an object (evaluating 'response.ok')". If anybody can advise on what the problem may be I would be greatly appreciative. Thank you in advance.

You should return a Promise from the second then(...) block so that the response is passed to the third then(...) block. You might want to try something like this:
// Fetch another API
return fetch('https://myremoteserveraddress', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(secondary),
})

Related

Node.js does not return value from post request

I am sending data to my node.js server using ajax:
btn.addEventListener("click",function () {
fetch("http://localhost:3000/buy", {
method: 'POST', // or 'PUT'
body: JSON.stringify({value:input.value}), // data can be `string` or {object}!
headers: {
'Content-Type': 'application/json'
}
}).then(function(res){
console.log("got it ", res)
return res.json();
})
.then(function(response){
console.log('Success:', JSON.stringify(response))
})
.catch(function(error ){
console.error('Error:', error)
})
})
and on my server i do following:
app.post('/buy' , ( req , res ) => {
console.log(req.body.value) // this prints right value
res.json({"foo":"bar"});
});
However my ajax code does not print anything, its like .then in promises is ignored.
Why is this happening? I dont see reason why this shouldnt work.
I am using express.js
Thanks for help!
btn.addEventListener("click",function () {
console.log('foo')
fetch("http://localhost:3000/buy", {
method: 'POST', // or 'PUT'
body: JSON.stringify({value:input.value}), // data can be `string` or {object}!
headers: {
'Content-Type': 'application/json'
}
}).then(function(res){
console.log("got it ", res)
return res.json();
})
.then(function(response){
console.log('Success:', JSON.stringify(response))
})
.catch(function(error ){
console.error('Error:', error)
})
})
Do you see 'foo' logged on the console?

axios delete method not working in react

i have tried to perform axios.delete operation in react, unfortunately it is not working, please help me to solve this issue,
export function DeletePatient(token,deletePatient) {
return axios.delete('/patient/billing_delete',deletePatient, {
headers: {
'Content-Type': 'application/json',
'token': token
}
})
.then(res => { console.log(token); return res.data })
.catch(err => { console.log(err); return err })
}
from my API response, i understood that my token is passed to backend, so i think i should change the structure of this code, please help me
the configuration object should come as second argument:
return axios.delete('/patient/billing_delete', {
headers: {
'Content-Type': 'application/json',
'token': token
},
data: deletePatient
})

React Native "fetch" returning server response without the information

I am using react native to create an application to act as a website that currently exists (with a user interface that works on a phone). i am using the "fetch" method to send a Http POST request to get information from a web server. The web server sends a response but it doesn't include the response message:
I apologies that is an image but the debugger is not working for me.
The code used to send the request:
HttpRequest = (RequestURL, callback) => {
var AdminLoginBindingModel = {
usr: this.state.username,
pwd: this.state.password,
}
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
callback(res);
})
.catch((error) => {
this.setState({Response: "Error: " + error});
})
}
The callback function in the parameters is just a function to change the state variable to display the information on the screen
ValidateResponse(response){
this.setState({Response: "Result: " + JSON.stringify(response),
displayMessage: "Success"});
console.log(JSON.stringify(response));
}
The Request being sent is "https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd="
The server responds with a json object regardless of a correct login or not
Edit:
Changing the response to
.then((res) => {
callback(res.json());
})
Result:
To get object from fetch response, you have to call res.json like following:
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json()) // HERE
.then(obj => callback(obj))
But it occurs an error because response body itself is invalid json format. It contains some HTML tags:
{"member": {"username":"","password":"","key":"***","status":"No"}}<br><br>Username: <br>Key: ***
Please check the inplementation of server.
EDIT: full code here
const fetch = require("node-fetch")
HttpRequest = (RequestURL, callback) => {
const AdminLoginBindingModel = { usr: "foo", pwd: "bar" }
fetch(RequestURL, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then(res => res.json())
.then(obj => callback(obj))
.catch(error => console.log(error))
}
const ValidateResponse = response => console.log(JSON.stringify(response))
URL = 'https://mibase-test.mibase.com.au/members/api/startSession.php?usr=&pwd='
HttpRequest(URL, ValidateResponse)
response doesn't contain received data directly. It provides interface methods to retrieve it. For example use response.json() to parse response text as JSON. It will return promise that resolves to the parsed object. You won't need to call JSON.parse on it:
fetch(RequestURL,
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(AdminLoginBindingModel)
})
.then((res) => {
return res.json();
}).then((obj) => {
console.log(obj);
});
Check https://developer.mozilla.org/en-US/docs/Web/API/Response and https://facebook.github.io/react-native/docs/network.html for more information.

Unable to perform POST request with fetch in react native

I am attempting to perform a POST operation on a json file being served by a json-server in node. I am receiving the following 500 error when attempting to perform said POST operation:
"TypeError: Cannot read property 'id' of undefined
at Function.createId"
The post operation is as follows:
pushState = () => {
var update = {
"a": 1,
"b": 2
};
return fetch(url, {
mode: 'cors',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(update)
})
.then((response) => {
console.log(response);
response.text();
})
.then((responseData) => {
console.log("Response:",responseData);
}).catch((error) => {
console.log(error);
})
.done();
}
Am I impementing the POST request correctly?
Edit: After adding async and await I'm still getting the same error:
pushState = async () => {
var update = {
"a": 1,
"b": 2
};
var result = await fetch(url, {
mode: 'cors',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(update)
})
.then((response) => {
console.log(response);
return response;
})
.catch((error) => {
console.log(error);
});
return result;
}
Two issues here:
You are not returning anything from fetch.
fetch is asynchronous. With the way you are calling it now with pushState returning a result immediately, it will almost always return undefined as you are getting in your error. You need write pushState using async/await.
Edit to answer comments:
Since you are using the function arrow syntax, making pushState asynchronous would look like this:
pushState = async () => { /* code */ }
To help you understand how fetch works, I recommend reading this first. Then to understand async/await at a high level, read this article. Your resulting code will look something like this:
pushState = async () => {
var update = {
"a": 1,
"b": 2
};
var result = await fetch(...) // Remember to return something.
return result;
}

Sending results from fetch to another part of program

I am creating an app in React Native and have bumped in to some major issues with fetching data from my server and using it in my program.
My architechture differs a bit from the example provided by React Native in their documentation, but I have tried a bunch of different ways. The token is correct and I am obviously calling the method in a sense correctly, but it does not return the data to the other side of my program.
In Methods.js
exports.loginUser = function(TOKEN) {
fetch(baseUrl + 'login' , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
accessToken: TOKEN,
},)
})
.then((response) => response.text())
.then((responseText) => {
console.log(typeof responseText);
return responseText
})
.catch((error) => {
console.warn(error);
});
};
Where it logs the type of the data as a string, and it prints out correctly when I call it as is. However, my app can't retrieve the data in any kind of manner, it just returns as undefined.
In Home.js
var Method = require('../Services/Methods');
.
.
.
var ComponentTwo = React.createClass({
getInitialState: function() {
return {
text: 'Loading...',
}
},
componentDidMount: function() {
{
this.setState({
text: Method.loginUser(AccessToken)
})
}
},
render: function() {
console.log(Method.loginUser(AccessToken));
console.log(this.state.text);
I am in trial and error mode right now, but both of the logs returns undefined, except for my log in Methods.js, so I think there is an issue with just hitting return responseText, but I don't know any other way since they are in two separate files. So I think the issue is within Method.JS since calling it fails in every way I've tried.
I think you have to return a promise from your loginUser function, something like:
exports.loginUser = function(TOKEN) {
return new Promise((resolve, reject) => {
fetch(baseUrl + 'login' , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
accessToken: TOKEN,
},)
})
.then((response) => response.text())
.then((responseText) => {
console.log(typeof responseText);
resolve(responseText);
})
.catch((error) => {
reject(error);
});
});
};
And then call your function like this:
Method.loginUser(AccessToken)
.then((res) => console.log(res))
.catch((error) => console.log(error))
.done();
I have not verified that the above code is working, it's just to give you an idea.

Categories

Resources