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.
Related
`I am using fetch on react native to send a post request with a form data object on the body.
This code works on iOS but on android it returns a 400 BAD REQUEST and I get ERROR [SyntaxError: JSON Parse error: Unexpected EOF].
const buildFormData = () => {
const data = new FormData();
for (let i = 0; i < photoForm.photosToUpload.length; i++) {
console.log(photoForm.photosToUpload[i].uri)
data.append('photosToUpload', {
uri: photoForm.photosToUpload[i].uri,
name: photoForm.photosToUpload[i].fileName,
type: 'image/jpeg'
});
data.append("userForm", JSON.stringify(userForm));
console.log(data)
return data;
}
This is how I am building my form data.
export const createUser = (formData) => async (dispatch) => {
try {
const headers = {
'Content-Type': 'multipart/form-data'
};
const response = await fetch('https://c66d-2a02-a03f-a5a1-e400-1573-78c6-e019-e601.eu.ngrok.io' + '/create_user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
})
.catch(error => {
console.error(error);
});
Handle successful response
catch (error) {
Handle error
}
This is how I am sending the form data to my django server. I know the problem is in the form data because if I dont send files the request goes through.
I have read almost every github issue on this matter, switched to axios, tried multiple solutions and no luck. Does anyone know what the problem can be?
I tried to make a post request using fetch and it works on iOS but not on android.
I was expecting to work on both OS.`
Here is my code:
const data = {
listing: listing,
};
await axios.post('https://app.jghfjgf.com/m/api/helper/helper', qs.stringify(data) ,{
headers:{
'Cookie':cookie,
'content-type': 'application/x-www-form-urlencoded'
}}
).then(response =>{
console.log(response);
alert(response.data);
}).catch(error => {
console.log(error);
alert(error);
});
I am trying to make HTTP request using Axios library and I tried most of the suggestions available on the web. I don't know what mistake I am doing. I am new to React Native application so don't have enough practice with Axios.
Note: The issue is value "cookie" in header is not passing along with the API so I am facing error.
react native fetch call (es5) returning undefined response. Here is the code of my fetch call.
body = {"username":"Gdgf","password":"dfgdfgdfg","remember":""}
var promise = new Promise(function(resolve, reject) {
fetch(`${FINAL_URL}users/login_app?app=1&submit=1`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
// 'content-type': 'application/x-www-form-urlencoded',
// 'content-Type': 'multipart/form-data'
},
body: JSON.stringify(body),
})
.then(response => response.json())
.then(responseData => console.log('responseData', responseData)) // console output is --> responseData []
.catch(err => {
reject(err);
});
});
attaching the screnshot of postman too, to show that api is working.
Most of the time this problem occurs when you don't call your end point correctly. As you said in the comments, in the console log of ${FINAL_URL}users/login_app?app=1&submit=1 you missed the www, which makes the response undefined. If you still have a problem please delete new Promise section from the fetch.
I hope I could help.
Can you try changing the following line:
then(responseData => console.log('responseData', responseData))
to
then(responseData => console.log('responseData', JSON.stringify(responseData)))
What is the console output now?
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.
i'm starting in react native and one thing i've been wondering is that, sometime i see fetch is used like this:
createTodo(){
fetch('http://192.168.1.34:3000/createTodo', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: this.state.noteText,
}),
}).then((response) => response.json())
.then((responseJson) => {
var d = new Date();
this.state.noteArray.push({
'date':d.getFullYear()+
"/"+(d.getMonth()+1) +
"/"+ d.getDate(),
'note': responseJson.data.content
});
this.setState({ noteArray: this.state.noteArray });
this.setState({noteText:''});
console.log(responseJson);
}).catch((error) => {
console.error(error);
console.log('Shit! Error occured');
});
}
this work fine.
and sometime it is:
return fetch(...)...
I'm a bit confused.
fetch is Promise which returns another Promise. Resolved results passed to next .then input parameters. So in your example code, you can handle response values which is passed by fetch function.
You can return your fetch function when the client of createTodo wants to use the 'result' of createTodo. The 'result' is another Promise whose input parameters are from createTodo's return values
demo link: https://codesandbox.io/s/548lwxzyn
Demo is just for showing that return value of Promise is another Promise. I hope you can get hint.