404错误:无法使用django rest框架提供静态React构建,除非我转到/index.html

维克树

我有一个React前端,我将其转换为静态文件。我曾经npm run build做过文件夹。然后我配置了Django Rest Framework:

settings.py

FRONTEND_ROOT = os.path.abspath(os.path.join(BASE_DIR, '..', 'frontend', 'build'))

urls.py

re_path(r'^(?P<path>.*)$', serve, { 'document_root': settings.FRONTEND_ROOT }),

当到达时localhost:8000,我会看到404页。如果说如何,我到了localhost:8000/index.html,那么我没有得到404,但是react应用程序。CSS和HTML虽然没有加载。

这是将静电反应连接到django后端的正确方法吗?我错过了一步吗?

普隆斯基

Djangoserve更适合在开发中提供静态文件:docs

为了进行开发,我只在一个终端中运行react dev服务器,在第二个终端中运行django dev服务器。

对于产品,您几乎没有选择来提供静态文件:

  • 看看WhiteNoise在Django中提供静态文件的服务(我在某个地方举例说明了如何配置它,但现在找不到它,请告诉我是否需要),
  • 将静态反应文件上传到S3并与CDN一起使用(在AWS部署和大流量的情况下)
  • 如果您想将所有内容都保留在一台机器上,那么我建议使用docker-compose。这是一个很好的解决方案,因为您可以与nginx进行交流。此外,您可以使用docker-compose从Let's Encrypt更新SSL证书。这是我正在使用的选项。在我的docker-compose下面。

我正在研究如何从头开始使用Django和React构建自己的SaaS应用程序的完整教程docker-compose来自教程。

# docker-compose
version: '2'

services:
    nginx: 
        restart: unless-stopped
        build:
            context: .
            dockerfile: ./docker/nginx/Dockerfile
        ports:
            - 80:80
            - 443:443
        volumes:
            - static_volume:/app/backend/server/django_static
            - ./docker/nginx:/etc/nginx/conf.d
            - ./docker/nginx/certbot/conf:/etc/letsencrypt
            - ./docker/nginx/certbot/www:/var/www/certbot
        depends_on: 
            - backend
    certbot:
        image: certbot/certbot
        restart: unless-stopped
        volumes:
            - ./docker/nginx/certbot/conf:/etc/letsencrypt
            - ./docker/nginx/certbot/www:/var/www/certbot
        entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"       
    backend:
        restart: unless-stopped
        build:
            context: .
            dockerfile: ./docker/backend/Dockerfile
        volumes:
            
        entrypoint: /app/docker/backend/wsgi-entrypoint.sh
        volumes:
            - .:/app
            - static_volume:/app/backend/server/django_static
        ports:
            - 8003:8003
        expose:
            - 8003        

volumes:
    static_volume: {}

nginx dockerfile分两个步骤:

  1. 建立反应
  2. 启动nginx
# nginx dockerfile
# build environment
FROM node:13.12.0-alpine as build

ADD ./frontend /app/frontend/
WORKDIR /app/frontend
RUN npm install
RUN npm run build

# production environment
FROM nginx:stable-alpine
COPY --from=build /app/frontend/build /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]

default.conf 文件

server {
    listen 80;
    server_name yourdomain.com;
    server_tokens off;

    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

server {
    listen 443 ssl;
    server_name yourdomain.com;
    server_tokens off;

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    client_max_body_size 20M;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }

    location /api {
        try_files $uri @proxy_api;
    }

    location @proxy_api {
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Url-Scheme $scheme;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_pass   http://backend:8003;
    }

    location /django_static/ {
        autoindex on;
        alias /app/backend/server/django_static/;
    }
}

django的dockerfile

FROM python:3.8.3-alpine

WORKDIR /app
ADD ./backend/requirements.txt /app/backend/


RUN pip install --upgrade pip
RUN pip install gunicorn
RUN pip install -r backend/requirements.txt

ADD ./backend /app/backend
ADD ./docker /app/docker

RUN rm -f /app/backend/server/db.sqlite3

wsgi-entrypoint.sh

#!/bin/sh

#ls -al /app/backend/server/static/client/static/js

until cd /app/backend/server
do
    echo "Waiting for server volume..."
done

until ./manage.py migrate
do
    echo "Waiting for db to be ready..."
    sleep 2
done

ls /app/backend/server

./manage.py collectstatic --noinput

gunicorn server.wsgi --bind 0.0.0.0:8003 --workers 4 --threads 4
#./manage.py runserver 0.0.0.0:8003  

init-letsencrypt.sh来自https://medium.com/@pentacent/nginx-and-lets-encrypt-with-docker-in-less-than-5-minutes-b4b8a60d3a71的脚本我强烈推荐这篇文章!

#!/bin/bash

if ! [ -x "$(command -v docker-compose)" ]; then
  echo 'Error: docker-compose is not installed.' >&2
  exit 1
fi

domains=(yourdomain.com www.yourdomain.com)
rsa_key_size=4096
data_path="./docker/nginx/certbot"
email="" # Adding a valid address is strongly recommended
staging=0 # Set to 1 if you're testing your setup to avoid hitting request limits

if [ -d "$data_path" ]; then
  read -p "Existing data found for $domains. Continue and replace existing certificate? (y/N) " decision
  if [ "$decision" != "Y" ] && [ "$decision" != "y" ]; then
    exit
  fi
fi


if [ ! -e "$data_path/conf/options-ssl-nginx.conf" ] || [ ! -e "$data_path/conf/ssl-dhparams.pem" ]; then
  echo "### Downloading recommended TLS parameters ..."
  mkdir -p "$data_path/conf"
  curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf > "$data_path/conf/options-ssl-nginx.conf"
  curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot/certbot/ssl-dhparams.pem > "$data_path/conf/ssl-dhparams.pem"
  echo
fi

echo "### Creating dummy certificate for $domains ..."
path="/etc/letsencrypt/live/$domains"
mkdir -p "$data_path/conf/live/$domains"
docker-compose run --rm --entrypoint "\
  openssl req -x509 -nodes -newkey rsa:1024 -days 1\
    -keyout '$path/privkey.pem' \
    -out '$path/fullchain.pem' \
    -subj '/CN=localhost'" certbot
echo


echo "### Starting nginx ..."
docker-compose up --force-recreate -d nginx
echo

echo "### Deleting dummy certificate for $domains ..."
docker-compose run --rm --entrypoint "\
  rm -Rf /etc/letsencrypt/live/$domains && \
  rm -Rf /etc/letsencrypt/archive/$domains && \
  rm -Rf /etc/letsencrypt/renewal/$domains.conf" certbot
echo


echo "### Requesting Let's Encrypt certificate for $domains ..."
#Join $domains to -d args
domain_args=""
for domain in "${domains[@]}"; do
  domain_args="$domain_args -d $domain"
done

# Select appropriate email arg
case "$email" in
  "") email_arg="--register-unsafely-without-email" ;;
  *) email_arg="--email $email" ;;
esac

# Enable staging mode if needed
if [ $staging != "0" ]; then staging_arg="--staging"; fi

docker-compose run --rm --entrypoint "\
  certbot certonly --webroot -w /var/www/certbot \
    $staging_arg \
    $email_arg \
    $domain_args \
    --rsa-key-size $rsa_key_size \
    --agree-tos \
    --force-renewal" certbot
echo

echo "### Reloading nginx ..."
docker-compose exec nginx nginx -s reload

我在这里粘贴了教程中的文件,因此您需要将目录结构更改为您自己的目录和域(抱歉!)。我仍在研究本教程。如果您有任何疑问,我们很乐意为您提供帮助。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用API中的HTML而不是index.html中的静态HTML来水化我的React应用

Django,使用nGinx提供静态文件时出现错误404

使用Django在Apache上提供静态文件(404错误)

除非我使用changeDetection onpush调用detectChanges(),否则HTML模板不会更新

Django静态文件无法解决常量404错误

无法通过web.xml从index.html调用/映射到servlet-错误-404

无法通过Spring Boot提供静态index.html

在Django中提供静态HTML

使用django / html中的静态文件进行下载可得到404

HTML页面加载缓慢,除非我省略了三个链接的静态文件之一

Django静态文件404错误

django rest框架如何禁用HTML错误页面的返回?

Django - 覆盖 base_site.html 后,我无法发布我的帖子并导致 CSRF 错误

扩展HTML上的Django静态块错误

无法使用 Express / Node 提供静态 HTML 文件

Python Plotly 静态图像导出(Orca)获取 html 错误 404

index.html的Apache2 404错误

使用Node.js错误404的angular-phonecat应用程序未找到:/app/index.html

React (Jumpsuit) - 除非我尝试/捕捉,否则错误不会显示在控制台中

Tomcat 服务器返回错误 404 ... 不,我不使用 web.xml、.jsp 或 .html 文件

我无法使用 SCSS 调整 HTML 输入占位符字体,是否有代码错误?

使用Gorilla Mux提供静态HTML

如何使用Rails提供静态html页面?

迁移后django静态文件404错误

django网站给静态文件404错误

Django 2.0中的错误404静态文件

Django静态文件突然消失404错误

我应该为React提供多少静态HTML?

使用 ssl 找不到静态文件 404 错误 - Django + uWSGI + nginx