Django CORS 请求仅在服务器上创建 403 禁止错误

时间:2021-05-05 12:48:08

标签: reactjs django django-rest-framework axios django-cors-headers

我有一个应用程序,它使用 Django 作为后端并为前端做出反应,所以我设置了 django-cors-headers。当我使用我添加的设置在本地测试应用程序时,我没有任何问题。但是我部署到我的服务器上,我一直在 API 请求(GET 请求除外)上收到 403 错误。

以下是我的 settings.py 文件(仅相关设置):

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '<my-secret-key>'

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

ALLOWED_HOSTS = ['<my-server-ip>']

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'frontend',
    'services',
    'rest_framework',
    'dj_rest_auth',
    'rest_framework.authtoken',
    'user',
    'corsheaders',
]

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',
]


STATIC_ROOT = os.path.join(BASE_DIR, 'static')

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    )
}

CORS_ALLOWED_ORIGINS = [
    "http://<my-server-ip>:8000",
    "http://localhost:8000",
    "http://127.0.0.1:8000",
    "http://0.0.0.0"
]

CSRF_TRUSTED_ORIGINS = [
    "http://<my-server-ip>:8000",
    "http://localhost:8000",
    "http://127.0.0.1:8000",
    "http://0.0.0.0"
]

CORS_ALLOW_CREDENTIALS = True

我使用 axios 以 axios.post('http://:8000/api-endpoint', body, config)then 的形式从 React 发出 API 请求em> 和 catch 块。

我得到的具体错误是:

xhr.js:177 POST http://<my-server-ip>:8000/api/auth/login/ 403 (Forbidden)

createError.js:16 Uncaught (in promise) Error: Request failed with status code 403
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

1 个答案:

答案 0 :(得分:0)

感谢 dbuchet,我发现这里的问题不是 CORS,而是在我的 settings.py 文件中,我将会话和令牌身份验证列为默认身份验证类 - 删除会话身份验证类解决了问题我有。

相关问题