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

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));

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

React native Expo project, Fetch the API will get [TypeError: Network request failed], but the others api can work

When I fetch the api in React native Expo project will get [TypeError: Network request failed].
I have try to fetch other API, it can get data success.
And also try to fix by this question but didn't work for me.
(Also tried this React Native fetch() Network Request Failed)
Is API's problem?
My code like:
const val = { uId: 'molly', pwd: '123', id: '1' }
const url = 'https://c........com.tw:8899'
let header = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(val),
}
fetch(`${url}/auth/login`, header)
.then((r) => r.json())
.then((d) => {
if (d.code === 0) {
console.log(d.data)
} else {
console.log('MSG', d.msg)
}
})
.catch((err) => console.log(err))
And I have try this, it can work. (So is not the network problem.)
fetch('https://randomuser.me/api/')
.then((r) => r.json())
.then((d) => {
console.log('ok')
})
.catch((err) => console.log(err))
Thanks for any suggestion.
I found the problem is about ssl.
Should use this package to deal with
react-native-ssl-pinning
https://www.npmjs.com/package/react-native-ssl-pinning

csrf issue in fetch API call from react native

I am using the following code from react-native mobile application to make a social authentication call to dj-rest-auth local link. However my Facebook authentication succeeds each time and then the fetch (or axios) local API call executes, which runs perfectly for the first time/run returning me the token but thereafter on every other runs, it gives me an error saying missing or invalid csrf token. I can't used the Django docs getCookie function as it gives Document error since this is a react-native mobile application. Please guide how to properly have API calls using csrf from the mobile app, with the code being used below (which is inside an async function):
fetch(
"http://192.168.1.102:8080/dj-rest-auth/facebook/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type':'application/json',
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken',
body:JSON.stringify({access_token:resolvedToken})
}
)
.then(resp => resp.json())
.then(data => {
console.log(data);
}
)
.catch(error => console.log(error))
The logout function also give the missing or invalid csrf error, which is written below for reference:
async function Logout() {
fetch(
"http://192.168.1.102:8080/dj-rest-auth/logout/",
{
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type':'application/json',
},
xsrfCookieName:"csrftoken",
xsrfHeaderName:'X-CSRFToken'
}
)
.then(resp => resp.json())
.then(data => {console.log(data)})
.catch(error => console.log(error))
}
The issue above is resolved by removing "Session Authentication" from your default REST authentication classes in settings.py and keeping the "Basic Authentication" and "Token Authentication" enabled.
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
Source: https://github.com/Tivix/django-rest-auth/issues/164#issuecomment-860204677

fetch error network on react native but working on postman

I'm currently developping a react-native app. Working on the login part,
I successfully made my call on postman with the right return but when fetching through react-native android client I get absolutly no return when calling the heroku server or even a network failed error when running the server locally.
What am I doing wrong ? I got absolutly no logs back from the code under.
const payloadJson = JSON.stringify({
email: 'julien#hypecode.com',
password: 'password',
})
fetch('https://alsatoju-dev.herokuapp.com/login', {
method: 'POST',
body: payloadJson,
headers: {
Accept: '*/*',
'Content-Type': 'application/json',
},
}).then((response) => {
console.log(response)
return response.json()
})
.then((res) => console.log(res))
.catch((err) => console.log(err))

React native fetch doesn't resolve or reject API request

I always get correct response from this request in my browser console:
fetch('http://178.62.66.29:8080/api/v1/auth/1/2', {
method: "GET",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then(response => response.json())
.then(responsejson => console.log(responsejson))
.catch(err => console.error(err));
But when I use the exact same code in React native (Android) the fetch function doesn't resolve or reject anything. The thing is, sometimes the fetch function works (Like 1/10) which makes this problem even more confusing to me.