如何将React Native应用与后端Django连接

huangapple go评论71阅读模式
英文:

How to connect react native app with backend django

问题

以下是你要翻译的内容:

"So I have a backend with django and I am using react native for frontend. I added an emulator in android studio.

And when I start the backend like: python manage.py runserver I can run also the frontend with expo start.

But now I want to fetch the data with react native. So I start the backend with: python manage.py runserver 192.168.1.68:19000 - settings file of django:

INSTALLED_APPS = [
    'corsheaders',
    'DierenWelzijnAdmin.apps.DierenwelzijnadminConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
]

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',
]
ALLOWED_HOSTS = ['192.168.1.68', '127.0.0.1', ]

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

CORS_ALLOW_METHODS = [
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
]

CORS_ALLOW_HEADERS = [
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
]

And react native service:

export const fetchCategoryData = async () => {
    try {
        const response = await fetch("http://192.168.1.68:19000/animal/categories/main_groups/", {
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
            },
        });
        if (!response.ok) {
            throw an Error("Network response was not ok");
        }

        return await response.json();
        //setCategoryData(data);
    } catch (error) {
        console.error("There was a problem with the fetch operation:", error);
        throw error;
    }
};

And when I then start the react native app with expo start and I do a r after a.

I get this message:

warn No apps connected. Sending "reload" to all React Native apps failed. Make sure your app is running in the simulator or on a phone connected via USB.

The emulator I installed from android studio is: Pixel 2 XL and if I do: adb devices I see the emulator:

List of devices attached
emulator-5554   device

And I already whiped the data several times from the emulator.

Question:

How to run the react native for fetching data from the backend?"

英文:

So I have a backend with django and I am using react native for frontend. I added a emulator in android studio.

And when I start the backend like: python manage.py runserver I can run also the frontend with expo start.

But now I want to fetch the data with react native. So I start the backend with:
python manage.py runserver 192.168.1.68:19000 - settings file of django:

INSTALLED_APPS = [
    'corsheaders',
    'DierenWelzijnAdmin.apps.DierenwelzijnadminConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
]

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',
]
ALLOWED_HOSTS = ['192.168.1.68', '127.0.0.1', ]

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

CORS_ALLOW_METHODS = [
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
]

CORS_ALLOW_HEADERS = [
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
]


And react native service:

export const fetchCategoryData = async () => {
	try {
		const response = await fetch("http://192.168.1.68:19000/animal/categories/main_groups/", {
			method: "GET",
			headers: {
				Accept: "application/json",
				"Content-Type": "application/json",
			},
		});
		if (!response.ok) {
			throw new Error("Network response was not ok");
		}

		return await response.json();
		//setCategoryData(data);
	} catch (error) {
		console.error("There was a problem with the fetch operation:", error);
		throw error;
	}
};

And when I then start the react native app with expo start and I do a r after a.

I get this message:

warn No apps connected. Sending "reload" to all React Native apps failed. Make sure your app is running in the simulator or on a phone connected via USB.

The emulator I installed from android studio is: Pixel 2 XL and if I do: adb devices
I see the emulator:

List of devices attached
emulator-5554   device

And I already whiped the data several times from the emulator.

Question:

How to run the react native for fetching data from the backend?

答案1

得分: 0

我已经更改了后端为:

192.168.1.68:8000

而且前端也是:

192.168.1.68:8000

现在可以正常工作了 如何将React Native应用与后端Django连接

这确实是我非常愚蠢的错误。因为我曾经获取了'//192.168.1.68:19000'。但那是我的模拟器主机。当然不会起作用。

英文:

Oke, I changed the backend to:

> 192.168.1.68:8000

and in frontend also:

> 192.168.1.68:8000

and it works now 如何将React Native应用与后端Django连接

This was indeed very stupid of me. Because I did fetch('//192.168.1.68:19000'). But that is my emulator host. Of course that doesn't work

huangapple
  • 本文由 发表于 2023年2月13日 23:38:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438064.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定