在Django中,从浏览器进行PUT请求时持续收到CORS错误。

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

Keep getting a CORS error for put requests in Django from browser

问题

以下是翻译好的内容:

我在从前端应用程序(使用Fetch API)向我的Django服务器发出PUT请求时不断收到CORS错误,但在Postman中没有问题。以下是错误信息:

跨域请求被阻止:同源策略不允许读取远程资源 https://q72y0iroi2.execute-api.us-west-2.amazonaws.com/weightsheets/636。 (原因:缺少CORS头'Access-Control-Allow-Origin')。状态码:503。

不知何故,GET、POST和DELETE请求都正常工作。

我已尝试了django-cors-headers文档中建议的所有设置,但无济于事!

任何建议将不胜感激。

这是我的settings.py文件内容。

英文:

I keep getting a CORS error when I make a put request to my Django server from my frontend application (Fetch API) but not from Postman. Here is the error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://q72y0iroi2.execute-api.us-west-2.amazonaws.com/weightsheets/636. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 503.

Somehow GET, POST and DELETE requests are working fine.

I have tried all the settings suggested in the documentation for django-cors-headers but to no avail!

Any advice would be highly appreciated

Here is my settings.py:

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())

DEBUG = os.getenv("DEBUG", "False")

ALLOWED_HOSTS = ['*']

DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False")


# 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',
    'corsheaders',
    'weighttrackingapi',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

# List of allowed origins

CORS_ALLOW_ALL_ORIGINS = True

CORS_ALLOW_METHODS = (
    "DELETE",
    "GET",
    "OPTIONS",
    "PATCH",
    "POST",
    "PUT",
)

CORS_ALLOW_HEADERS = (
    "accept",
    "authorization",
    "content-type",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",
)
CORS_ALLOW_CREDENTIALS = True



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


ROOT_URLCONF = 'weighttracking.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 = 'weighttracking.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'railway',
        'USER' : 'postgres',
        'PASSWORD' : '*****************',
        'HOST' : 'containers-us-west-11.railway.app',
        'PORT' : '7866',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.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',
    },
]


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True



STATIC_URL = 'static/'
# STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT =os.path.join(BASE_DIR, 'staticfiles')

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

答案1

得分: 1

DEBUG = True

ALLOWED_HOSTS = ["*"]

# 应用程序定义

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders', # <-------- 这部分
    'myapp',
]

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',
    'sales_company_app.get_user_instance.RequestMiddleware',
]

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

CORS_ORIGIN_ALLOW_ALL = True # <-------- 这部分
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",    # React (前端 URL) # <-------- 这部分
]

CORS_ALLOW_HEADERS = '*' # <-------- 这部分
CSRF_TRUSTED_ORIGINS = ["http://192.168.1.155:8000/"] # (Api 基础 URL) <-------- 这部分

### 注意 - 确保已安装 (pip install django-cors-headers)
英文:
DEBUG = True

ALLOWED_HOSTS = [&quot;*&quot;]


# Application definition

INSTALLED_APPS = [
    &#39;django.contrib.admin&#39;,
    &#39;django.contrib.auth&#39;,
    &#39;django.contrib.contenttypes&#39;,
    &#39;django.contrib.sessions&#39;,
    &#39;django.contrib.messages&#39;,
    &#39;django.contrib.staticfiles&#39;,
    &#39;rest_framework&#39;,
    &#39;corsheaders&#39;, # &lt;-------- this
    &#39;myapp&#39;,
]

MIDDLEWARE = [
    &#39;django.middleware.security.SecurityMiddleware&#39;,
    &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,
    &#39;corsheaders.middleware.CorsMiddleware&#39;, # &lt;-------- this
    &#39;django.middleware.common.CommonMiddleware&#39;,
    &#39;django.middleware.csrf.CsrfViewMiddleware&#39;,
    &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,
    &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,
    &#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,
    &#39;sales_company_app.get_user_instance.RequestMiddleware&#39;,
]



REST_FRAMEWORK = {
    &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (
        &#39;rest_framework.authentication.TokenAuthentication&#39;,
    ),
}


CORS_ORIGIN_ALLOW_ALL = True # &lt;-------- this
CORS_ALLOWED_ORIGINS = [
    &quot;http://localhost:3000&quot;,    # React (FrontEnd Url) # &lt;-------- this
]

CORS_ALLOW_HEADERS = &#39;*&#39; # &lt;-------- this
CSRF_TRUSTED_ORIGINS = [&quot;http://192.168.1.155:8000/&quot;] # (Api Base Url) &lt;-------- this

NOTE - Make sure must installed (pip install django-cors-headers)

答案2

得分: 0

只需将您的站点添加到Access-Control-Allow-Origin标头中,一切都会没问题。只需像这样执行:

Access-Control-Allow-Origin: 您域名的URL

或者

Access-Control-Allow-Origin: *

我不建议使用底部的选项,除非您知道自己在做什么。

参考链接是:CORS错误代码503

英文:

Just add your site to the Access-Control-Allow-Origin header and you'll be fine. Just do something like

Access-Control-Allow-Origin: url/of/your/domain

or

Access-Control-Allow-Origin: *

I would not recommend doing the bottom one unless you know what you are doing.

Reference would be this: CORS error code 503

huangapple
  • 本文由 发表于 2023年5月29日 23:08:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76358438.html
匿名

发表评论

匿名网友

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

确定