![](/img/trans.png)
[英]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.