[英]How to use Apache to serve Django server and React client?
[英]How can I have Django serve React using Apache2 on Ubuntu 18.04?
我正在嘗試在 Ubuntu 18.04 上使用 Apache2 部署帶有 React 前端的 Django 應用程序。 React 應用程序由 Django 通過staticfiles
應用程序提供服務。 對於上下文,讓我們從 Django 如何為 React 服務開始。
以下代碼來自nerd-rich-django-back-end/nerdrich/urls.py
。
from homepage.views import index
url_patterns = [
path('', index, name=index),
]
接下來我們有nerd-rich-django-back-end/homepage/views.py
from django.views.generic import TemplateView
from django.views.decorators.cache import never_cache
index = never_cache(TemplateView.as_view(template_name='build/index.html'))
使用此配置,Django 將在用戶訪問根端點時為 React 應用程序提供服務。 這在開發中有效,但是當我嘗試在生產中復制它時,我遇到了一些問題。 即...這是我在 Apache2 中使用的站點 - /etc/apache2/sites-available/000-default-le-ssl.conf
<Directory /home/jakuta/.venv/bin/djangoprojects/nerd-rich-django-back-end/nerdrich>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
<Directory /home/jakuta/.venv/bin/djangoprojects/nerd-rich-django-back-end/nerd-rich-front-end/build>
Require all granted
</Directory>
DocumentRoot 指令被刪除,Django 應用程序運行良好,因為還有其他端點需要測試,比如使用 DRF 的 API 端點。 但是當向https://nerdrich.net/發出請求時,只有一個空白頁面。 如果您導航到https://nerdrich.net/jakuta,您將獲得可瀏覽的 API。
有關其他上下文,以下是 Django nerd-rich-django-back-end/nerdrich/settings.py
CORS_ORIGIN_WHITELIST = [
'http://localhost:3000'
'http://localhost:5000'
] # used in development -- not sure how to use in production since Django now serves React
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'nerd-rich-front-end')],
'APP_DIRS': True,
'OPTIONS': # the default Options are set here
}
]
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'nerd-rich-front-end', 'build', 'static'),
)
同樣,對原生 Django 端點發出的請求工作正常,但是當請求來自 React 構建版本的 html 頁面時,該頁面是空白的。 如果我錯過了任何需要的其他信息,請告訴我。
這是我從 Apache 配置中遺漏的內容,即,因為我已經通過 LetsEncrypt 配置了 SSL,這是我需要添加到/etc/apache2/sites-available/000-default-le-ssl.conf
Alias /static /home/jakuta/.venv/bin/djangoprojects/nerd-rich-django-back-end/nerd-rich-front-end/build/static
<Directory /home/jakuta/.venv/bin/djangoprojects/nerd-rich-django-back-end/nerd-rich-front-end/build/static>
Require all granted
</Directory>
Apache 必須配置為在build/static
文件夾中提供 React 的靜態文件。 否則,React 將無法工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.