我对 Django Rest Framework 与 React 的集成有疑问。我仔细地遵循了所有设置步骤,并且在运行服务器后,我的网站(包括博客详细信息)在浏览器中完美呈现。
但是,我遇到了一个问题:当我刷新内部页面(主页刷新没有任何问题)时,我在这些页面上看到 JSON 数据,而不是预期的内容。您能否就此事提供一些指导?
谢谢你。
我将以下代码放入 Django 的设置文件中:
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
REAL_BASE_DIR = Path(__file__).resolve().parent.parent.parent
# Other codes
ROOT_URLCONF = 'backend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(REAL_BASE_DIR, 'frontend', 'build')],
'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',
],
},
},
]
STATIC_URL = 'static/'
STATICFILES_DIRS = [os.path.join(REAL_BASE_DIR, 'frontend', 'build', 'static')]
CKEDITOR_UPLOAD_PATH = 'uploads/' # Adjust the path as needed
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
所有端点在 React 中都工作正常,只要我浏览网站就没有问题。但是当我重新加载内部页面时,会显示 JSON 数据。
我最初通过添加以下代码来更新 URL 配置,为 React 应用程序的 index.html 提供任何不匹配的 URL 模式:
# Define a catch-all route to serve the React application's index.html
re_path(r'^.*', TemplateView.as_view(template_name='index.html')),
但是,这导致内部页面重新加载 JSON 数据而不是预期的内容。 为了解决这个问题,我修改了代码如下,成功地将一些内部页面(例如帖子列表和每个帖子的详细信息)链接到重新加载时各自的端点:
# Serve React's index.html for all unmatched URLs
re_path(r'^.*$', TemplateView.as_view(template_name='index.html')),