django项目前后端分离跨域配置


创建django项目

django-admin startproject 项目名称

例如:

django-admin startproject mydjango

创建app应用

python manage.py startapp 应用名称

例如:

python manage.py startapp myapp

注册应用路由(打开mydjango项目文件的urls.py)

from django.contrib import admin
from django.urls import path,include  #导入include包

urlpatterns = [
   path('admin/', admin.site.urls),
   path('myapp/', include('myapp.urls')), #注册应用路由
]

配置Django跨域请求处理

1、安装DRF

pip install djangorestframework

2、安装cors组件

pip install django-cors-headers

3、django配置文件(settings.py)安装corsheaders、rest_framework应用和添加中间件同时注册app应用

INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'corsheaders',
   'rest_framework',
   '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',
]

#设置跨域
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True

4、数据库的配置

DATABASES = {
  'default': {
         'ENGINE': 'django.db.backends.mysql', #数据库引擎
         'NAME': 'edu',                       #数据库名
         'USER': 'root',                       #用户名
         'PASSWORD': 'root',                   #密码
         'HOST': '',                           #数据库主机,默认为localhost
         'PORT': '',                           #数据库端口,MySQL默认为3306
         'OPTIONS': {
            'autocommit': True,
        }
   }
}

5、settings.py中静态文件的配置(可选)

STATIC_URL = '/static/'

STATICFILES_DIRS=[
    os.path.join(BASE_DIR,'static')
]

#定义上传文件夹的路径
UPLOAD_ROOT = os.path.join(BASE_DIR,'static/upload')

在myapp应用中的views.py中写入逻辑

from django.shortcuts import render

# Create your views here.
from django.views import View
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView


class Index(APIView):
   def get(self, request):
       pass

       return Response({'code':200})
   def post(self,request):
       pass

       return Response({'code':200})

注册视图(views.py)路由,进入myapp应用创建urls.py文件

from django.urls import path
from myapp.views import Index  #导入views.py中的Index类,并注册路由
urlpatterns = [
   path('index/',Index.as_view()),

]

myapp应用中的models.py定义模型

from django.db import models

class User(models.Model):
   username = models.CharField(max_length=128, verbose_name='用户名')
   password = models.CharField(max_length=128, verbose_name='密码')
   class Meta:
        db_table = "user"
        verbose_name = '用户表'
        verbose_name_plural = verbose_name

将模型提交到数据库中

python manage.py makemigrations

python manage.py migrate

启动django项目

python manage.py runserver 0.0.0.0:8000