简体   繁体   English

使用 Django 后端在前端获取 CORS 错误

[英]Getting CORS error in frontend with Django backend

From my frontend http://127.0.0.1:5500/index.html I am calling Django REST POST API http://127.0.0.1:8000/api .从我的前端http://127.0.0.1:5500/index.html我打电话给 Django REST POST API http://127.0.0.1:8000/api I have installed django-cors-headers and my frontend's image_upload.js , backend's settings.py , and views.py , project level urls.py and app level urls.py are as follows, API is working in postman but I am getting CORS error in chromes console,我已经安装了 django-cors-headers 和我的前端的image_upload.js ,后端的settings.pyviews.py ,项目级urls.py和应用程序级urls.py如下, API 在 postman 工作,但我得到 CORS chrome 控制台错误,

Chrome console

在此处输入图像描述

Django console

在此处输入图像描述

image_upload.js

const image_input = document.querySelector("#image_input");
const display_image = document.querySelector("#display-image");
image_input.addEventListener("change", (event) => {
  console.log(event.target.files[0]);
  // console.log(URL.createObjectURL(event.target.files[0]));
  display_image.src = URL.createObjectURL(event.target.files[0]);

  const url = "http://127.0.0.1:8000/api";
  const data = event.target.files[0];

  axios
    .post(url, JSON.stringify(data), {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
});

settings.py

"""
Django settings for model project.

Generated by 'django-admin startproject' using Django 2.2.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

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 = 'pd^*8)+5$qr_q9(a+n)(meh22&m=0+qn7a^g8$#&)(+fv!1wgc'

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

ALLOWED_HOSTS = ['http://127.0.0.1:5500']


# Application definition

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

    # 3rd party
    'rest_framework',
    "corsheaders",

    # Local
    'apis.apps.ApisConfig',
]

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

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


# CORS_ALLOWED_ORIGINS = [
#     'http://127.0.0.1:8000',
# ]

# CSRF_TRUSTED_ORIGINS = [
#     'http://127.0.0.1:8000',
# ]

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/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/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

CORS_ORIGIN_ALLOW_ALL: True

# CORS_ALLOW_CREDENTIALS = True

# CORS_ALLOWED_ORIGINS = [
#     'http://127.0.0.1:8000/api/',
#     'http://127.0.0.1:5500',
# ]

CORS_ORIGIN_WHITELIST = [
    'http://127.0.0.1:5500',
    # 'http://127.0.0.1:8000',
]

# CORS_ALLOW_HEADERS = ['*']

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

views.py

from email import message
from tkinter import image_names
from django.shortcuts import render
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework import status
from rest_framework.decorators import api_view

from tensorflow.keras.models import load_model
import urllib.request

# Create your views here.

@api_view(['GET', 'POST'])
def PostRequests(request):
  print(request.body)
  # ing_url = ''
  # img_name = "tumor_image.jpg"
  # img = urllib.request.urlretrieve(img_url,img_name)
  # print(img)
  # loaded_model = load_model("vgg16_model_with_90_acc.h5")
  return JsonResponse({'message': "It Worked!"}, safe=False)

Project level urls.py项目级urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('apis.urls')),
]

App level urls.py应用级urls.py

from django.urls import path


from apis import views


urlpatterns = [
  path('', views.PostRequests),
]

in your settings.py file you should convert this在你的 settings.py 文件中你应该转换这个

CORS_ORIGIN_WHITELIST = [
'http://127.0.0.1:5500'
]

to this:对此:

CORS_ALLOWED_ORIGINS=[
      "http://127.0.0.1:5500"
 ]

 

Change CORS_ORIGIN_ALLOW_ALL: True to CORS_ALLOW_ALL_ORIGINS=True.将 CORS_ORIGIN_ALLOW_ALL: True 更改为 CORS_ALLOW_ALL_ORIGINS=True。 That may be one problem.这可能是一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM