前后端都要运行哦
需要axios库,DjangoRestFramework,django,vue-cli,django-cors-headers
npm install axios
//main.ts
import axios from 'axios'
var app = createApp(App);
app.config.globalProperties.$url = 'http://127.0.0.1:8000/';
app.config.globalProperties.$axios = axios;
app.use(router).mount('#app')
pip install djangorestframework
pip install django-cors-headers
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'toResponse', # 你注册的app 名称
'corsheaders', # 加上
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', #加上
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', # 注释掉
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
// HTML部分
// js 部分
//router目录下的 index.ts
import index from '@/views/index.vue'
const routes: Array = [
{
path: '/',
name: 'index',
component: index,
},
]
//HTML部分
// js部分
# settings.py
import os
# 下面这些话放在文件末尾
JSON_FILE_PATH = os.path.join(BASE_DIR , 'rear\json') # 定义读取文件的路径
# 设立白名单 运行http://localhost:8080 端访问
CORS_ORIGIN_WHITELIST = [
'http://localhost:8080',
]
# toResponse 下的 views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import JsonResponse
from rear import settings
# Create your views here.
class DataTest(APIView):
def get(self, request, *args, **kwargs):
data = getjson()
return JsonResponse(data,safe=False)
def getjson():
files = []
with open(settings.JSON_FILE_PATH + "\红楼梦.json","r",encoding='utf-8') as f:
data = f.read() # 读取该目录下的红楼梦.json文件,可自己改
return data
# rear目录下的 urls.py
from django.contrib import admin
from django.urls import path
from toResponse import views
urlpatterns = [
path('admin/', admin.site.urls),
path('course/', views.DataTest.as_view()),
]