【问题标题】:Cannot fetch API data after deploying application to Heroku (works perfectly locally)将应用程序部署到 Heroku 后无法获取 API 数据(在本地完美运行)
【发布时间】:2021-06-28 16:40:41
【问题描述】:

部署到 Heroku 后,我无法从我的 Django Rest API 公开获取数据。它在本地完美运行。当我点击 heroku 网页 -> Inspect -> Console 时,显示“加载资源失败:net::ERR_CONNECTION_REFUSED”和“未捕获(承诺)TypeError:失败获取”。

该 API 公开位于 heroku 上,它正确地拥有我的所有数据 (https://xxxxxxxxxx.herokuapp.com/api)。

我正在使用 Django 后端和 ReactJS 前端。

Settings.py

import os
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 = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['xxxxxxxxxxxxx.herokuapp.com', '127.0.0.1']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    'rest_framework',

    'backend',

    'corsheaders',
]


REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ]
}

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',
    
    'whitenoise.middleware.WhiteNoiseMiddleware',
]

ROOT_URLCONF = 'xxxxxxxxxxxxx.urls'


TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'reactapp/build'),
        ],
        '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 = 'xxxxxxxxxxxxx.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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'reactapp/build/static'),
]   

CORS_ORIGIN_WHITELIST = [
    "http://localhost:3000", "http://127.0.0.1:8000", "https://xxxxxxxxxxxxx.herokuapp.com",
]

App.js

  fetchTasks(){
    fetch('https://xxxxxxxxxx.herokuapp.com/api')
    .then(response => response.json())
    .then(data =>
      this.setState({
        todoList:data
      })
      )
  }

【问题讨论】:

  • 听起来问题出在 CORS(跨域资源共享)上?
  • 是否可以使用 CURL 或 POSTMAN ?

标签: javascript reactjs django heroku django-rest-framework


【解决方案1】:

解决了!我犯了一个愚蠢的错误。我的数据是从我的本地 API 而不是我的公共 API 获取的。我将代码更改为公开获取,但忘记在终端中运行“npm run build”。

【讨论】:

    猜你喜欢
    • 2017-09-27
    • 2022-01-14
    • 2015-08-05
    • 2020-10-22
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2015-10-25
    相关资源
    最近更新 更多