I have a django application and I have a react native app. I am running the android emulator from android studio.
And now I try to connect the backend with the frontend. I studied the example from: https://reactnative.dev/docs/network
And the example url: https://reactnative.dev/movies.json' works.
I run the native-react app on port: http://192.168.1.69:19000/ And I run the backend on port: http://127.0.0.1:8000/api/movies/
But now I try to connect with my own localhost data. So this is my component:
import { ActivityIndicator, FlatList, Text, View } from "react-native";
import React, { Component } from "react";
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: true,
};
}
async getMovies() {
try {
const response = await fetch("http://127.0.0.1:8000/api/movies/", {
method: "GET",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
const json = await response.json();
this.setState({ data: json.movies });
} catch (error) {
console.log(error);
} finally {
this.setState({ isLoading: false });
}
}
componentDidMount() {
this.getMovies();
}
render() {
const { data, isLoading } = this.state;
return (
<View style={{ flex: 1, padding: 24 }}>
{isLoading ? (
<ActivityIndicator />
) : (
<FlatList
data={data}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => <Text>{item.title}</Text>}
/>
)}
</View>
);
}
}
this is the data from postman:
[
{
"id": 1,
"title": "Husband",
"description": "Very nice wife cocks the man",
"no_of_ratings": 1,
"avg_rating": 5.0
},
{
"id": 2,
"title": "Nice movie",
"description": "Description ah, niceNICE",
"no_of_ratings": 0,
"avg_rating": 0
}
]
But if I try to run this example. I get this error:
Access to fetch at 'http://127.0.0.1:8000/api/movies/' from origin 'http://localhost:19006' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Question: how to make a connection from native react witht the backend?
Oke, I installed:django.cors.headers and in settings I did all the configuration.
So in django I have this:
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
]
and in react native I have this:
useEffect(() => {
fetch("http://127.0.0.1:8000/animalGroups/group/", {
method: "GET",
})
.then((res) => res.json())
.then((jsonres) => setAnimalGroup(jsonres))
.catch((error) => console.error(error));
}, []);
and the native react app is running on:
› Opening exp://192.168.1.69:19000 on MY_ANDROID
So but I still get this error:
Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0