我们通过django-cors-headers处理跨域问题
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app', 'corsheaders', //添加app ]添加中间件corsheaders.middleware.CorsMiddleware
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]在setting.py中配置跨域规则
CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'VIEW', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', )npm run dev启动node服务器
通过npm run build打包前端到dist目录,用于后续django链接。
三、django链接到前端调整django_vue目录下路由urls.py如下
from django.contrib import admin from django.urls import path,include from django.views.generic import TemplateView //导入通用视图 import app.urls urlpatterns = [ path('admin/', admin.site.urls), path('api/',include(app.urls)), path('',TemplateView.as_view(template_name="index.html")), //路由到index.html ]在setting.py下添加静态文件地址
STATICFILES_DIRS = [(os.path.join(BASE_DIR,'appfront/dist/static'))]启动django 服务
python manage.py runserver访问我们的django地址,此时django已链接到前端
参考:https://github.com/rogerlh/django_with_vue
NEXTdjango-rest-framework 创建restful api
django wsgi的应用
文章有不足的地方欢迎在评论区指出。
欢迎收藏、点赞、提问。关注顶级饮水机管理员,除了管烧热水,有时还做点别的。