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

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

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:

  1. BASE_DIR = Path(__file__).resolve().parent.parent
  2. SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())
  3. DEBUG = os.getenv("DEBUG", "False")
  4. ALLOWED_HOSTS = ['*']
  5. DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False")
  6. # Application definition
  7. INSTALLED_APPS = [
  8. 'django.contrib.admin',
  9. 'django.contrib.auth',
  10. 'django.contrib.contenttypes',
  11. 'django.contrib.sessions',
  12. 'django.contrib.messages',
  13. 'django.contrib.staticfiles',
  14. 'rest_framework',
  15. 'rest_framework.authtoken',
  16. 'corsheaders',
  17. 'weighttrackingapi',
  18. ]
  19. REST_FRAMEWORK = {
  20. 'DEFAULT_AUTHENTICATION_CLASSES': (
  21. 'rest_framework.authentication.TokenAuthentication',
  22. ),
  23. 'DEFAULT_PERMISSION_CLASSES': [
  24. 'rest_framework.permissions.IsAuthenticated',
  25. ],
  26. }
  27. # List of allowed origins
  28. CORS_ALLOW_ALL_ORIGINS = True
  29. CORS_ALLOW_METHODS = (
  30. "DELETE",
  31. "GET",
  32. "OPTIONS",
  33. "PATCH",
  34. "POST",
  35. "PUT",
  36. )
  37. CORS_ALLOW_HEADERS = (
  38. "accept",
  39. "authorization",
  40. "content-type",
  41. "user-agent",
  42. "x-csrftoken",
  43. "x-requested-with",
  44. )
  45. CORS_ALLOW_CREDENTIALS = True
  46. MIDDLEWARE = [
  47. 'corsheaders.middleware.CorsMiddleware',
  48. 'django.middleware.common.CommonMiddleware',
  49. 'django.middleware.security.SecurityMiddleware',
  50. 'django.contrib.sessions.middleware.SessionMiddleware',
  51. 'django.middleware.csrf.CsrfViewMiddleware',
  52. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  53. 'django.contrib.messages.middleware.MessageMiddleware',
  54. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  55. ]
  56. ROOT_URLCONF = 'weighttracking.urls'
  57. TEMPLATES = [
  58. {
  59. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  60. 'DIRS': [],
  61. 'APP_DIRS': True,
  62. 'OPTIONS': {
  63. 'context_processors': [
  64. 'django.template.context_processors.debug',
  65. 'django.template.context_processors.request',
  66. 'django.contrib.auth.context_processors.auth',
  67. 'django.contrib.messages.context_processors.messages',
  68. ],
  69. },
  70. },
  71. ]
  72. WSGI_APPLICATION = 'weighttracking.wsgi.application'
  73. # Database
  74. # https://docs.djangoproject.com/en/4.1/ref/settings/#databases
  75. DATABASES = {
  76. 'default': {
  77. 'ENGINE': 'django.db.backends.postgresql',
  78. 'NAME': 'railway',
  79. 'USER' : 'postgres',
  80. 'PASSWORD' : '*****************',
  81. 'HOST' : 'containers-us-west-11.railway.app',
  82. 'PORT' : '7866',
  83. }
  84. }
  85. # Password validation
  86. # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
  87. AUTH_PASSWORD_VALIDATORS = [
  88. {
  89. 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
  90. },
  91. {
  92. 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
  93. },
  94. {
  95. 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
  96. },
  97. {
  98. 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
  99. },
  100. ]
  101. LANGUAGE_CODE = 'en-us'
  102. TIME_ZONE = 'UTC'
  103. USE_I18N = True
  104. USE_TZ = True
  105. STATIC_URL = 'static/'
  106. # STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
  107. STATIC_ROOT =os.path.join(BASE_DIR, 'staticfiles')
  108. # Default primary key field type
  109. # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
  110. DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

答案1

得分: 1

  1. DEBUG = True
  2. ALLOWED_HOSTS = ["*"]
  3. # 应用程序定义
  4. INSTALLED_APPS = [
  5. 'django.contrib.admin',
  6. 'django.contrib.auth',
  7. 'django.contrib.contenttypes',
  8. 'django.contrib.sessions',
  9. 'django.contrib.messages',
  10. 'django.contrib.staticfiles',
  11. 'rest_framework',
  12. 'corsheaders', # <-------- 这部分
  13. 'myapp',
  14. ]
  15. MIDDLEWARE = [
  16. 'django.middleware.security.SecurityMiddleware',
  17. 'django.contrib.sessions.middleware.SessionMiddleware',
  18. 'corsheaders.middleware.CorsMiddleware', # <-------- 这部分
  19. 'django.middleware.common.CommonMiddleware',
  20. 'django.middleware.csrf.CsrfViewMiddleware',
  21. 'django.contrib.auth.middleware.AuthenticationMiddleware',
  22. 'django.contrib.messages.middleware.MessageMiddleware',
  23. 'django.middleware.clickjacking.XFrameOptionsMiddleware',
  24. 'sales_company_app.get_user_instance.RequestMiddleware',
  25. ]
  26. REST_FRAMEWORK = {
  27. 'DEFAULT_AUTHENTICATION_CLASSES': (
  28. 'rest_framework.authentication.TokenAuthentication',
  29. ),
  30. }
  31. CORS_ORIGIN_ALLOW_ALL = True # <-------- 这部分
  32. CORS_ALLOWED_ORIGINS = [
  33. "http://localhost:3000", # React (前端 URL) # <-------- 这部分
  34. ]
  35. CORS_ALLOW_HEADERS = '*' # <-------- 这部分
  36. CSRF_TRUSTED_ORIGINS = ["http://192.168.1.155:8000/"] # (Api 基础 URL) <-------- 这部分
  37. ### 注意 - 确保已安装 (pip install django-cors-headers)
英文:
  1. DEBUG = True
  2. ALLOWED_HOSTS = [&quot;*&quot;]
  3. # Application definition
  4. INSTALLED_APPS = [
  5. &#39;django.contrib.admin&#39;,
  6. &#39;django.contrib.auth&#39;,
  7. &#39;django.contrib.contenttypes&#39;,
  8. &#39;django.contrib.sessions&#39;,
  9. &#39;django.contrib.messages&#39;,
  10. &#39;django.contrib.staticfiles&#39;,
  11. &#39;rest_framework&#39;,
  12. &#39;corsheaders&#39;, # &lt;-------- this
  13. &#39;myapp&#39;,
  14. ]
  15. MIDDLEWARE = [
  16. &#39;django.middleware.security.SecurityMiddleware&#39;,
  17. &#39;django.contrib.sessions.middleware.SessionMiddleware&#39;,
  18. &#39;corsheaders.middleware.CorsMiddleware&#39;, # &lt;-------- this
  19. &#39;django.middleware.common.CommonMiddleware&#39;,
  20. &#39;django.middleware.csrf.CsrfViewMiddleware&#39;,
  21. &#39;django.contrib.auth.middleware.AuthenticationMiddleware&#39;,
  22. &#39;django.contrib.messages.middleware.MessageMiddleware&#39;,
  23. &#39;django.middleware.clickjacking.XFrameOptionsMiddleware&#39;,
  24. &#39;sales_company_app.get_user_instance.RequestMiddleware&#39;,
  25. ]
  26. REST_FRAMEWORK = {
  27. &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: (
  28. &#39;rest_framework.authentication.TokenAuthentication&#39;,
  29. ),
  30. }
  31. CORS_ORIGIN_ALLOW_ALL = True # &lt;-------- this
  32. CORS_ALLOWED_ORIGINS = [
  33. &quot;http://localhost:3000&quot;, # React (FrontEnd Url) # &lt;-------- this
  34. ]
  35. CORS_ALLOW_HEADERS = &#39;*&#39; # &lt;-------- this
  36. 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标头中,一切都会没问题。只需像这样执行:

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

或者

  1. 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

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

or

  1. 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:

确定