¿为什么我在Django中的CORS配置无法正常工作?

时间:2020-08-28 15:28:26

标签: python django api rest heroku

我的production.py文件中有我的REST API设置。该REST API已上传到Heroku,并使用django-cors-headers并具有以下配置:

# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Third-Party apps
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'gunicorn',
    
    # Local apps
    'core',
    'users',
    'checkers',
]

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

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
    'myapi.herokuapp.com'
)

将myapi.herokuapp.com放入CORS_ORIGIN_WHITELIST时的想法是查看是否拒绝来自localhost的请求(这样做是正确的)。但这是可以接受的,这使我了解到CORS不能很好地工作。

1 个答案:

答案 0 :(得分:0)

在获取Django rest_api之前,请确保在后端django-cors-headers中设置settings.py。有关更多信息,请查看此link

pip install django-cors-headers

settings.py:

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]
MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
    ...
    'corsheaders.middleware.CorsMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
    ...
]

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
    'your-server-IP-address'
)
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]