Home > Back-end >  connecting react native with django, fetching data
connecting react native with django, fetching data

Time:01-20

I just try to connect the native react app with the django backend.

So in Django I installed the django.cors.headers. And i did the configuration in settings.

I am using android studio. And I am using the emulator. And that works fine.

And I have the settings for the cors in django:

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]


CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = [
    "http://localhost:8081",
    "http://localhost:19006",
    "http://localhost:19002",
    "http://192.168.1.69:19000",
]

and react native

useEffect(() => {
        fetch("http://127.0.0.1:8000/animalGroups/group/", {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
        })
            .then((res) => res.json())
            .then((jsonres) => setAnimalGroup(jsonres))
            .catch((error) => console.error(error));
    }, []);

So in postman it runs fine:

I get the correct response:

[
    {
        "group_name": "zoogdieren",
        "description": "Dit zijn zoogdieren"
    },
    {
        "group_name": "vissen",
        "description": "Dit is de hoofgroep vissen"
    }
]

and this are the messages in react native:

 Opening on Android...
› Opening exp://192.168.1.69:19000 on MY_ANDROID
› Press ? │ show all commands
› Reloading apps
Android Bundling complete

But I still get this errors:

Network request failed
at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _allocateCallback$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue

So what I have to change?

Thank you

CodePudding user response:

Salut,

Ton problème réside au niveau de l'url. Ton émulateur et ton serveur doivent être connectés sur le même réseau. Les émulateurs mobile comme Android studio ou même Xcode ne font pas les appels en localhost(127.0.0.1)

Pour ce fait, tu vas connecter ton ordinateur un réseau (l'accès internet n'est pas requis).

Tu interroges l'adresse ip de ta machine sur le réseau (sous windows c'est ipconfig, sous Linux c'est ip address)

En fin du démarre le serveur django sur l'adresse ip. exemple :

python manage.py runserver 125.568.97.65:8000

Tu reviens dans react native et tu remplaces:

useEffect(() => {
    fetch("http://125.568.97.65:8000/animalGroups/group/", {
        method: "GET",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
        },
    })
        .then((res) => res.json())
        .then((jsonres) => setAnimalGroup(jsonres))
        .catch((error) => console.error(error));
}, []);

Bonne chance

CodePudding user response:

Your problem lies in the url. Your emulator and server must be connected on the same network. Mobile emulators such as Android studio or even Xcode do not make calls in localhost(127.0.0.1)

To do this, you will connect your computer to a network (internet access is not required).

You query the ip address of your machine on the network (under windows it's ipconfig, under Linux it's ip address)

At the end of the start the django server on the ip address. example:

python manage.py runserver 125.568.97.65:8000

You come back to react native and you replace:

useEffect(() => {
    fetch("http://125.568.97.65:8000/animalGroups/group/", {
        method: "GET",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
        },
    })
        .then((res) => res.json())
        .then((jsonres) => setAnimalGroup(jsonres))
        .catch((error) => console.error(error));
}, []);

Good luck

  • Related