Consider:
InsertDataToServer = () => {
const { pinValue1 } = this.state;
const { pinValue2 } = this.state;
const { pinValue3 } = this.state;
const { pinValue4 } = this.state;
var String_3 = pinValue1.concat(" ", pinValue2);
var String_4 = String_3.concat(" " , pinValue3);
var String_5 = String_4.concat(" " , pinValue4);
fetch("http://www.aonde.biz/mobile/doLogin.php", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
"pin": 212,
})
})
.then(response => response.json())
.then(responseJson => {
// Showing the response message coming from
// the server after inserting records.
Alert.alert(responseJson);
})
.catch(error => {
console.error(error);
});
In the above code, when I pass the "pin" parameter API, it shows this error:
How can I resolve this issue?
This error was fixed when the code changed from:
Alert.alert('Error:', error)
to:
Alert.alert('Error:', error.message)
In your Alert.alert(responseJson);, you need to stringify it like this:
Alert.alert(JSON.stringify(responseJson));
Keep in mind that alert is a component from the mobile app, so it might not understand the code shown there is JSON content. If that doesn't work, use responseJson.text().
Make sure your alerts are displaying the error.MESSAGE and not the whole error. Depending on the error and its type that might be the cause!
That was the cause of my issue.
The error was fixed when adding the title in the Alert method.
As in the documentation, the title of Alert must be given while calling the Alert method.
I have had a similar issue. I solved it by changing one of the syntax. In your case, try this:
fetch("http://www.aonde.biz/mobile/doLogin.php",
method: "POST",
header: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
"pin":212,
})
)
What I changed to your coding: I removed {} after the URL.
If you get a red line error on the :, then remove method: header: and body: as well. The code will be like this:
fetch("http://www.aonde.biz/mobile/doLogin.php",
"POST",
{
Accept: "application/json",
"Content-Type": "application/json"
},
JSON.stringify({
"pin":212,
})
)
You can check if its string before sending it to Alert.alert method:
const title = "Error title..";
const errorMessage = (typeof error === 'string' || error instanceof String) ? error : error.message;
Alert.alert(title, errorMessage);
I was having this error because I installed a library that needed me to compile the app again and I hadn't compiled it.
After compiling again everything worked fine.
You can simply remove double quotation marks from pin.
fetch("http://www.aonde.biz/mobile/doLogin.php", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
pin:212,
})
})
Related
I'm trying to POST data with FormData to get a response, on iOS it works as expected, but on android, it always goes to the catch block, I found out the reason for that is response.json() with error: [SyntaxError: JSON Parse error: Unrecognized token '']
Here is my code:
const onAndroidSucks = () => {
setLoading(true);
let formData = new FormData();
formData.append("number", number.replace(/\s+/g, '').substring(4));
formData.append("id", userID);
formData.append("token", userToken);
fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: formData
}).then(response => response.json()).then(response => {
if (response.res === 'no') {
Alert.alert('ჰეჰე');
} else {
setData(response);
}
setLoading(false);
}).catch(err => { Alert.alert(err.message); setLoading(false); } );
};
I don't understand what the actual problem is here.
It turned out that problem was okHttp on android. Looks like okHttp appends an empty string " " without a known reason.
Here is how I solved that issue with the workaround:
}).then(response => response.text())
.then((res) => JSON.parse(res.trim())).then(response => {
I am trying to call from fetch request but I am passing parameters on request is fine but when I checked server-side getting null data I am unable to understand whats exact problem after I research i found that charset=utf-8 need to mention so I did still having the same issue.
const request = {
videoId: data.videoId,
comments: data.comments,
views: parseInt(data.views) + 1,
likes: data.likes,
shares: data.shares
}
alert(JSON.stringify(request));
fetch(URL + '/VideosController/updateVideo', {
method: 'POST', // or 'PUT'
headers: {
'Accept': 'application/json',
'content-Type': "application/json; charset=utf-8" // "text/html; charset=UTF-8",
},
body: JSON.stringify(request),
})
.then(response => response.json())
.then((postsJson) => {
alert('res1 + ' + JSON.stringify(postsJson));
})
.catch((error) => {
alert('Error:', JSON.stringify(error));
});
Im trying to post an Image to server but axios throw an error saying
[Error: Network Error]
I created a bodyFormData and appended the following
bodyFormData.append('image', {
name: imgName,
type: 'image/jpeg',
uri: this.state.image,
});
where my imageName is just a string and the this.state.image is the file path file:///storage/emulated/0/Pictures/0cccb0f1-375b-44b8-b15b-4625536a8d63.jpg
Axios Call
const addProduct = async product => {
try {
var prod = await axios({
method: 'post',
url: baseURL + 'addProduct',
data: product,
headers: {
'content-type': `multipart/form-data; boundary=${product._boundary}`,
Accept: 'application/json',
},
},
});
return prod;
} catch (err) {
throw err;
}
};
after alot of trials i understand that in bodyFormData even i write any kind of json object
const oj = {
name: 'a',
c: 8,
}
bodyFormData.append('image', obj );
it throws me the same error
[Error: Network Error]
Kindly please drop the best possible solution for the problem
Thank you for your precious time.
I recently implemented this (working) code
const formData = new FormData();
formData.append('file', {
type: 'image/jpeg',
name: `myname.jpeg`,
uri: isAndroid() ? uri : uri.replace('file://', ''),
});
and with this header in the api call
'Content-Type': 'multipart/form-data'
It's very similar to your code - maybe the uri part then ?
I'm trying to send a fetch request using post to an api, I'm doing a search using a keyword and it should return a JSON containing users, whenever I try this on Android using expo it doesn't work however it seems to work on iOS using expo. The error I get back is a JSON parse error, I get a status code of 308.
import User from '../../Model/User';
import { BearerToken } from '../../Constants/BearerToken';
export const GETRESULTS = 'GETRESULTS';
export const getResults = (item) => {
return async dispatch => {
const response = await fetch("https://example.com",
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': BearerToken
},
body: JSON.stringify({
query: item
}),
redirect: 'follow'
}
);
console.log(response.status);
if(!response.ok) {
console.log("fack off");
const errorResData = await response.json();
console.log(errorResData);
let message = 'Something went wrong';
throw new Error(message);
}
const resData = await response.json();
const searchResultsArray = [];
for(const searchResult in resData){
searchResultsArray.push(new User(
resData[searchResult].education,
resData[searchResult].email,
resData[searchResult].full_name,
resData[searchResult].gender,
resData[searchResult].job_title,
resData[searchResult].location,
resData[searchResult].password,
resData[searchResult].phone,
resData[searchResult].preferred_name,
resData[searchResult].profile_image,
resData[searchResult].profile_type,
resData[searchResult].score,
resData[searchResult].short_bio,
resData[searchResult].story
)
);
}
dispatch({type: GETRESULTS,usersArray:searchResultsArray});
};
};
What worked for me was putting 'https://example.com/search/' basically at a slash at the end fixed it for me
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Trying to call an API to my backend with Fetch, but I can't access the response body. There's a loot of different notation and syntax about this on the internet and I can't figure out how to do it properly.
I've tried response.json() and responseJson, and stringyfying both. I don't get what I want which is the actual body of the response. It's meant to have a key/token that I then save.
responseJson returns this: responseJson:
{"_40":0,"_65":0,"_55":null,"_72":null}
This is my function:
export function LogIn(em, pass) {
return (dispatch) => {
console.log('LogIn called');
dispatch(logInIsLoading(true));
//from phone
*fetch('http://192.168.1.18:8080/rest-auth/login/', {
method: 'POST',
headers: {
// 'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'email': em,
'password': pass,
})
}).then((response) => {
console.log("response " + JSON.stringify(response));
if (!response.ok) {
console.log("ERROR: " + response.statusText);
throw Error(response.statusText);
}
dispatch(logInIsLoading(false));
return response;
})
.then((response) => {
responseJson = response.json();
console.log("responseJson: " + JSON.stringify(response.json()));
return responseJson
})
.then((responseJson) => {
AsyncStorage.multiSet([['key', responseJson.key], ['loggedIn', true]], () => {
console.log(responseJson.key);
dispatch(isLoggedIn(true));
dispatch(getKey(responseJson.key));
});
})*
.catch(() => dispatch(logInHasErrored(true)));
};
}
This is the response, but I can't get to the key in the body:
response {"type":"default","status":200,"ok":true,"headers":{"map":
{"allow":["POST, OPTIONS"],"set-cookie":
["csrftoken=DOMxD5IhNz5Vwm9a3niAR1tRyqBfNzUqnQMAEgk7AGwtwCgnRnZo9x0AMTM2IfK
q; expires=Fri, 22-Feb-2019 17:31:58 GMT; Max-Age=31449600; Path=/,
sessionid=er3fujv8ji96t41n1n8dlzb3zz1itwuj; expires=Fri, 09-Mar-2018
17:31:58 GMT; httponly; Max-Age=1209600; Path=/"],"content-type":
["application/json"],"content-length":["50"],"x-frame-options":
["SAMEORIGIN"],"vary":["Accept, Cookie"],"server":["WSGIServer/0.1
Python/2.7.14"],"date":["Fri, 23 Feb 2018 17:31:58
GMT"]}},"url":"http://192.168.1.18:8080/rest-auth/login/","_bodyInit":"
{\"key\":\"a9951fd6abff4fed35d9a8d1c275bf1212887513\"}","_bodyText":"
{\"key\":\"a9951fd6abff4fed35d9a8d1c275bf1212887513\"}"}
response.json() return Promise
AsyncStorage.multiSet - return Promise. Second parameter of multiSet is Function that will be called with an array of any key-specific errors found
export function LogIn(em, pass) {
return (dispatch) => {
console.log('LogIn called');
dispatch(logInIsLoading(true));
fetch('http://192.168.1.18:8080/rest-auth/login/', {
method: 'POST',
headers: {
// 'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'email': em,
'password': pass,
})
}).then((response) => {
if (!response.ok) {
console.log("ERROR: " + response.statusText);
throw Error(response.statusText);
}
dispatch(logInIsLoading(false));
return response;
})
.then((response) => {
return response.json()
})
.then((responseJson) => {
console.log('responseJson', responseJson);
return AsyncStorage.multiSet([['key', responseJson.key],['loggedIn', true]], () => {
dispatch(logInHasErrored(true));
})
.then(() => {
dispatch(isLoggedIn(true));
dispatch(getKey(responseJson.key));
})
})
.catch(() => dispatch(logInHasErrored(true)));
};
}
This is pretty straight forward with axios.
First install axios by doing npm install --save axios
Then inside your Component do this:
handleInput = async() => {
const res = await axios.post('http://192.168.1.18:8080/rest-auth/login/', {
email: this.state.email,
password: this.state.password
});
const data = await res.json();
console.log(data);
}
Make sure you've stored email and password in this.state.email and this.state.password respectively and call handleInput when user presses the Submit button.
Don't forget to import axios import axios from 'axios'