React Native: Fetching from API gives: Unexpected End Of JSON File - react-native

I am using React Native Expo and I am trying to fetch data from Fantasy API but when I parse the fetched data to JSON it says SyntaxError: Unexpected end of JSON input. This is the code I use for fetching:
fetch("https://fantasy.premierleague.com/api/bootstrap-static/", {
method: "GET",
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then((res) => {
return res.json();
})
.then((data) => {
console.log("DATA: ", data);
})
.catch((err) => {
console.log("Error: " + err);
});
Please add into consideration that the data is fetched properly when I use postman.
The provided code works for other APIs. I do not know why it does not work with this one.

Get request don't need headers so remove it and it will work.

Related

Fetch Post of formData with images works in iOS but on android returns 400 BAD REQUEST

`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.`

Error trying to fetch access token from Spotify API using Axios

I'm working on a project with Vue using the Spotify API and get stuck trying to get the access token. I'm using axios to make the request but every time I get a 400 status from the server.
This is the way I'm doing it, I have the request inside an action in my Vuex store and I'm not sure if I'm missing something.
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
params: {
grant_type: 'authorization_code',
code: payload.code,
redirect_uri: process.env.VUE_APP_REDIRECT_URI
},
headers: {
'Authorization': 'Basic ' + (new Buffer(process.env.VUE_APP_CLIENT_ID + ':' + process.env.VUE_APP_CLIENT_SECRET).toString('base64')),
'Content-Type': 'application/x-www-form-urlencoded'
},
json: true
})
.then((response) => {
//handle success
resolve(response);
})
.catch((error) => {
//handle error
reject(error);
})
I would try using data instead of params.
I think data is for the POST body and params is for query string parameters.
Axios Cheat Sheet
You should inspect the request to see what you're sending and then compare that to what you should be sending.

React Native - Can't get data from asp.net web api

I'm building an app using React Native with Expo and an ASP.Net Web API.
I'm using two computers: one I published the Web API on it and using it as a server which has the IP 192.168.1.9 ,
and the other one with IP 192.168.1.6 I'm using for developing.
The problem is when I ping the server computer I get a reply and when I use postman I get the data I requested,
but when I run the app using Expo on my Android Phone, the request enters the catch and returns an error.
Here is the code:
var url = 'http://192.168.1.9/trainlast/api/Login';
fetch(url,
{
method: 'GET',
})
.then(response => { response.json(); })
.then(users => {
this.setState({ allUsers: users });
})
.catch(error => console.error('Error getting users :: ', error));
I have tried everything I could possibly think of, but no use.
Can someone tell me what the problem is? thank you .
You can configure Accept and Content-Type of headers.
And get the correct value for the object.
var url = 'http://192.168.1.9/trainlast/api/Login';
fetch(url,
{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
})
.then((response) => response.json())
.then(res => {
this.setState({ allUsers: res.Username });
})
.catch(error => console.error('Error getting users :: ', error));

Empty response data for fetch call

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?

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...