Post data to API in React Native only show empty - api

I am building an application in react native CRNA for the front-end side and using PHP for the backend side. But when I tried to post a data, for example login form, the result is only empty no matter what the given input is.
This is an example of my snippet code.
fetch('someURL', {
method: 'POST',
headers: {
"Content-Type": "application/json",
'Accept': 'application/json',
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
message: this.state.message,
})
})
.then((response)=>response.json())
.then((responseData)=>{
Alert.alert(console.log(responseData))
return responseData;
}).catch((error) => {
console.error(error);
});
}
I tried to check the value with console.log and didn't get anything (only empty).. What should I do? Can anyone please tell me what's wrong? Thank you so much.

Try to remove the first then() and put the response.json() into the next then(). In the same block as the Alert.

Related

How to check if body in fetch POST has sent to API in react native?

I am building a react native app and got this following error. I want to send inputted message, email, and name to API, but it's not showing any result in API.
Here is the code:
fetch('localserverusingIPaddress', {
method: 'POST',
headers: {
"Content-Type": "application/json",
'Accept': 'application/json',
},
body: JSON.stringify({
name: this.state.name,
email: this.state.email,
message: this.state.message,
}),
})
.then((response)=> {console.warn(response.json())})
//{
// if (response.status){
// return response.json();
// }
// console.warn(response.json())
// return response.json();
//})
//console.warn(response);
//response.json()
//console.warn(JSON.parse(response))})
.then((responseData)=>{
this.showAlert();
console.warn(responseData);
return responseData;
})
.catch((error) => {
console.warn(error);
});
However, when I try to check the inputted texts in iOS
simulator, it's showing the value. It's also showing the values when I post data to API directly with postman. So I start to think that the body was failed to pass to API.
Can anyone please tell me why is this happening and how to fix this? Thank you so much, I'm facing this problem for several weeks...
First step is to make sure if your iOS simulator is actually able to make requests to your localhost or not. If it can't reach your local network, it must throw some kind of connectivity error. However, from your comment above, it seems that is not an issue.
Try this code:
let url = 'localserverusingIPaddress';
let requestObject = {
name: this.state.name,
email: this.state.email,
message: this.state.message
};
try {
let response = await fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(requestObject)
});
responseJson = await response.json();
console.log(responseJson);
} catch (error) {
console.error(error);
}
Try this and see what is the logged output.
Easiest way to see if the request has actually reached your API is from the API end itself. Your server must have some sort of event logging implemented. See what happens there when you make a request from Postman and compare its output with what happens when you make a request from the app.

POST fails with ReadableNativeMap cannot be cast to String error

I'm working in React Native, I use PHP for backend and when I use fetch POST request I get so strange error, and I dont know why it happens. I checked the url so it works no problem, also normal fetch() is working without POST but when I try to post it happens. When I try it in local server fetch POST works.. but in server, I get this error :
ERROR : com.facebook.react.bridge.ReadableNativeMap cannot be cast to
java.lang.String
React native codes :
fetch('http://xxx/react_test1', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: inputName,
email: inputEmail,
phone: inputPhone
}),
}).then((response) => response.json())
.then((responseJson) => {
Alert.alert(responseJson);
}).catch((error) => {
alert(error);
});
Alert.alert receives an string, and what you're getting from the fetch response is internally a com.facebook.react.bridge.ReadableNativeMap object (which is what the native implementation for fetch returns).
You can try:
Alert.alert(JSON.stringify(responseJson))
If you were using iOS you'll get a completely different error:
Exception '-[_NSFrozenDictionaryM length]: unrecognized selector ...
Alert.alert only accepts string as input.
Use alert() instead to show the popup.
Example: alert("Response: ", responseJson)
Happy Coding. :)
So with fetch() in javascript you need headers: {} but when switching over to RNFetchBlob you should put the headers directly in the {}
import RNFetchBlob from "rn-fetch-blob";
const aPath = Platform.select({ ios: DocumentDir, android: DownloadDir });
const fPath = aPath + '/' + Math.floor(date.getTime() + date.getSeconds() / 2) + '.xls';
Also if you want to add body in the request then directly add it there.
For example:-
RNFetchBlob.config({
// response data will be saved to this path if it has access right.
path: fPath,
}).fetch('POST', URL, {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: token,
},
JSON.stringify(reqBody)
)
.then(res => {
console.log("response body>>>",res);
})
.catch(function (err) {
console.log(err);
});
that's all enjoy your coding...

axios react native implementation

I got some issue on axios react native,
axios({
method: 'post',
url: url+endPoint,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer '+token,
},
data: data
})
.then((response) => {
let cities = response.data.city || [];
console.log('success', response.data.city);
this.setState({
visible: false
})
})
.catch((error) => {
console.log('error');
this.setState({
visible: false
})
});
When axios error if I set let cities = response.data.city || []; on success, block error wont called, axios will executed success block instead error.
Whats wrong with my code or it is bug from axios ?or I need do something ?
I hope react native master here can help me for this issue.
response.data.city
The above code is trying to read the city in response data. if there is no response data or city information then the catch block will execute.
Please check the response is correct or not or the data you are trying to read is available or not.

How to send data to server and fetched response using react native application?

I am trying to learn react native application by making a simple login page using api call. Where I will send user name and password to api and it will give me response. But I can't do it. Well I am sharing my code here.....
var myRequest = new Request('<my API >', {method: 'POST', body: '{"username":this.state.uName , "password":this.state.pwd}'});
fetch(myRequest).then(function(response) {
alert('Res'+response);
}).then(function(response) {
alert('Blank'+response);
})
.catch(function(error) {
alert('Error'+error);
});
I think the way of passing my user name and password to server is wrong. Please give me some idea then I can understand what is wrong here.
var data = {
"username": this.state.username,
"password": this.state.password
}
fetch("https://....", {
method: "POST",
headers: headers,
body: JSON.stringify(data)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
I hope this helps.
You need to Stringify the json data to send request as Post method with Json parameters as you are trying to do...
Here is the example code for how to encode data before requesting for response
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
Here is the sample code for login :
fetch(<hostURL>, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ userName: <userName> ,Password: <Password>,})
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData);
}).catch((error) => {
console.log("Error");
});
As the commentators before me stated, you simply need to stringify your JSON Body. In general, I' suggest that you incorporate e.g. api sauce into you stack. It is a comprehensive wrapper around the axios library, providing standardized errors and an ok key for quick checks.

How do i get the status of my response when using fetch in react-native?

I am making Log In page for my react native application. My api sends different response when my username and password are valid and invalid. So I want to track and save the status of my response in some state variable and then later perform function accordingly. Please suggest me way to do that.
doSignUp() {
console.log("inside post api");
fetch('MyApiUrl', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
password: this.state.password,
email:this.state.email,
name: this.state.firstname,
last_name :this.state.last_name,
mobile:this.state.mobile,
ssn:"2222222"
})
}).then((response) => {console.log('response:',response.status);
response.json()}
.then((responseData) => {
console.log("inside responsejson");
console.log('response object:',responseData)
console.log('refresh token:',responseData[0].token.refresh_token)
console.log('access token:',responseData[0].token.access_token);
}).done();
}
As far as I understand you want to know the http status code of your fetch request.
Usually your response object includes a "status" property. So you should be able to receive the status code by using this:
response.status
In case of a successful request this will return 200.