如何解决无法连接Django和我的本机应用程序... [网络请求失败]
我无法从我创建的其余API到我的React Native应用程序的响应。即使我运行django服务器,其余的api仍在运行,但是我无法从其余的API获得响应。在邮递员上工作的请求,我可以在那里获得响应,但在React Native应用中无法获得响应。我在下面附加了我的代码。请仔细检查
反应本机代码
useEffect(() => {
fetch('http://localhost:8000/api/movies/')
.then(res => console.log(res.json))
.catch(err => console.log(err));
},[]);
settings.py
"""
Django settings for movietracker project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file,see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values,see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'v23d&&w#*&g4q+mse7nbby4rms79(r7@feg&j1d*wf=3vq8)&4'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework','rest_framework.authtoken','api'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware','django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]
ROOT_URLCONF = 'movietracker.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [],'APP_DIRS': True,'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug','django.template.context_processors.request','django.contrib.auth.context_processors.auth','django.contrib.messages.context_processors.messages',],},]
WSGI_APPLICATION = 'movietracker.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3','NAME': BASE_DIR / 'db.sqlite3',}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS,JavaScript,Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
# CORS Config
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
解决方法
根据他们的文档(https://pypi.org/project/django-cors-headers/),您还应该将corsheader添加到install_apps。
INSTALLED_APPS = [
'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','rest_framework','rest_framework.authtoken','corsheaders','api'
]
还要添加
# Corsheaders settings
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
CORS_ORIGIN_WHITELIST = (
'*'
)
,
我就是这样解决的。
1 - 打开命令提示符并输入:
ipconfig
然后复制粘贴您的 IPv4 地址,例如 ('182.167.2.65')
2 - 将以下代码行添加到 settings.py:
ALLOWED_HOSTS += '182.167.2.65'
CORS_ORIGIN_ALLOW_ALL = True # Change it in production and specify your own origins
3 - 按如下方式运行服务器:
py manage.py runserver 0.0.0.0:8000
4 - 现在在反应中向这个方向获取:
'182.167.2.65' ## This direction is just an example (put your IPv4)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。