- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试将我的 react/django web-app 部署到 linux-VM droplet。我没有为 JS 内容使用 webpack。相反,我通过 CDN 子域、 digital ocean s3 存储桶提供 npm run build
静态文件。
我能够 python manage.py collectstatic
然后将我的 React 生产构建文件夹推送到 CDN。
当我访问我的生产网站时,它目前只是加载了一个包含这些控制台错误的空白页面:
Refused to apply style from 'https://www.my_website_URL.com/static/css/main.ce8d6426.chunk.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Refused to execute script from 'https://www.my_website_URL.com/static/js/2.ca12ac54.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
Refused to execute script from 'https://www.my_website_URL.com/static/js/main.220624ac.chunk.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
没有任何网络错误可以为此事提供任何有用的信息。
问题必须是服务器端(django)...我认为。
项目设置:
React 生产构建在我的核心 django 文件夹中。
以下是我如何通过 django 链接我的 React:
核心 urls.py
def render_react(request):
return render(request, "index.html")
#index.html being created by react, not django templates
urlpatterns = [
re_path(r"^$", render_react),
re_path(r"^(?:.*)/?$", render_react),
...
]
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
{% comment %} <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> {% endcomment %}
<link
rel="stylesheet"
href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css"
/>
<script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
settings.py
import os
from pathlib import Path
from decouple import config
import dj_database_url
from datetime import timedelta
# Build paths inside the project like this: BASE_DIR / 'subdir'.
# BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('DJANGO_SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['URL's']
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_HTTPONLY = True
INSTALLED_APPS = [
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third Party Apps #
'django_filters',
'corsheaders',
'django_extensions',
'drf_yasg',
'storages',
# Apps
'users',
'bucket',
'bucket_api',
#oauth
'oauth2_provider',
'social_django',
'drf_social_oauth2',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'oauth2_provider.middleware.OAuth2TokenMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'core.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS' : [os.path.join(BASE_DIR, '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',
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]
WSGI_APPLICATION = 'core.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': config('DJANGO_DB_NAME'),
'USER' : config('DJANGO_DB_ADMIN'),
'PASSWORD' : config('DJANGO_ADMIN_PASS'),
'HOST' : config('DJANGO_DB_HOST'),
'PORT' : config('DJANGO_DB_PORT'),
'OPTIONS': {'sslmode':'disable'},
}
}
db_from_env = dj_database_url.config(conn_max_age=600)
DATABASES['default'].update(db_from_env)
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/New_York'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
AWS_S3_ENDPOINT_URL = config('AWS_S3_ENDPOINT_URL')
AWS_S3_CUSTOM_DOMAIN = config('AWS_S3_CUSTOM_DOMAIN')
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_LOCATION = config('AWS_LOCATION')
AWS_DEFAULT_ACL = 'public-read'
STATIC_URL = '{}/{}/'.format(AWS_S3_ENDPOINT_URL, AWS_LOCATION)
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static/templates'),
os.path.join(BASE_DIR, 'build/static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
如何修复我的 Django 以从我的 CDN 正确地提供生产静态 block css 和 js 文件?如果 Chrome 控制台能够在错误中找到文件,CDN 的路径和位置必须正确。
如果您需要我这边的更多信息,请告诉我。目前卡住了,没有一个简单的解决方案来修复我的 MIME 类型错误并解决我的网站仅加载空白页面的问题。
感谢您提供任何帮助/提示/或指导!
如果有人想知道,我正在使用 Gunicorn 和 Nginx。
编辑:添加了赏金以提请注意此问题。我没有使用 Django webpack loader 和 babel。我宁愿不依赖其他可能轻易破坏事物的库。
编辑#2:我已经添加了我的 NGINX 配置文件,我应该将流量重定向到我的 CDN 路径吗?
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 301 https://my_website_URL.io$request_uri;
}
server {
listen [::]:443 ssl ipv6only=on;
listen 443 ssl;
server_name my_website_URL.com www.my_website_URL.com;
# Let's Encrypt parameters
ssl_certificate /etc/letsencrypt/live/my_website_URL.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/my_website_URL.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
location = /favicon.ico { access_log off; log_not_found off; }
location / {
proxy_pass http://unix:/run/gunicorn.sock;
proxy_redirect off;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
}
编辑编辑编辑:我已经添加了我的 gunicorn 文件,因为我得到了一个 502 错误的网关并且我的 gunicorn 服务给我这个错误:
● gunicorn.socket - gunicorn socket
Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled)
Active: failed (Result: service-start-limit-hit) since Wed 2021-04-28 23:44:16 UTC; 1min 2s ago
Triggers: ● gunicorn.service
Listen: /run/gunicorn.sock (Stream)
这是我的 gunicorn 配置:
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=alpha
Group=www-data
WorkingDirectory=/home/user/srv/project/backend
ExecStart=/home/user/srv/project/backend/venv/bin/gunicorn \
--access-logfile - \
--workers 3 \
--timeout 300 \
--bind unix:/run/gunicorn.sock \
core.wsgi:application
[Install]
WantedBy=multi-user.target
最佳答案
静态文件 URL 是由 React 而不是 Django 生成的。所以即使STATIC_URL
如果设置正确,静态文件的 URL 不会在 Django 中被模板化,例如使用 {% static '' %}
.
根据您的 TEMPLATES
设置,Django 正在从 npm run build
(而不是 index.html
在问题中)。 index.html
中指向 CSS 和 JavaScript 文件(也由 React 构建)的 /static
URL 由 React 而不是 Django 生成。
要让 React 生成具有正确前缀的 URL,您可以设置 PUBLIC_URL
运行 npm run build
之前的环境变量。目前它将使用默认设置(即主机的根 /
)。
如果您在主机上提供静态文件或使用 {% static '' %}
,您收到的错误将是一个问题。供引用:
您的一个 URL 过于贪婪:
re_path(r"^(?:.*)/?$", render_react),
这将匹配:
static/css/main.ce8d6426.chunk.css
因此该 URL 将解析为您的 render_react
View 并尝试为您的 index.html
文件提供服务,因此它认为 MIME 类型为 text/html
:
Refused to apply style from 'https://www.my_website_URL.com/static/css/main.ce8d6426.chunk.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
如果您想匹配除以 static
开头的所有 URI,您可以在正则表达式中使用否定先行:
re_path(r"^(?!static)(?:.*)/?$", render_react),
在您的 settings.py 中,您将覆盖 STATIC_URL
设置,该设置将 Django 定向到您的静态文件 CDN:
STATIC_URL = '{}/{}/'.format(AWS_S3_ENDPOINT_URL, AWS_LOCATION)
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = '/static/' # <------- REMOVE
此外,STATIC_URL
需要在前面加上 https://
并使用 AWS_S3_CUSTOM_DOMAIN
(不是 AWS_S3_ENDPOINT_URL
):
STATIC_URL = f'https://{AWS_S3_ENDPOINT_URL}/{AWS_LOCATION}/'
您的 NGINX 和 Gunicorn 配置没有问题。您的 Django 应用程序可能无法正常启动,例如,由于配置错误:
查看日志:
journalctl -u gunicorn.service
运行简单的冒烟测试(是否打开?)也很有用:
./manage.py runserver
关于javascript - 如何通过 Django 正确地服务于我的 React 生产构建。当前配置存在 MIME 类型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67271401/
我正在尝试编写一个相当多态的库。我遇到了一种更容易表现出来却很难说出来的情况。它看起来有点像这样: {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE
谁能解释一下这个表达式是如何工作的? type = type || 'any'; 这是否意味着如果类型未定义则使用“任意”? 最佳答案 如果 type 为“falsy”(即 false,或 undef
我有一个界面,在IAnimal.fs中, namespace Kingdom type IAnimal = abstract member Eat : Food -> unit 以及另一个成功
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: What is the difference between (type)value and type(va
在 C# 中,default(Nullable) 之间有区别吗? (或 default(long?) )和 default(long) ? Long只是一个例子,它可以是任何其他struct类型。 最
假设我有一个案例类: case class Foo(num: Int, str: String, bool: Boolean) 现在我还有一个简单的包装器: sealed trait Wrapper[
这个问题在这里已经有了答案: Create C# delegate type with ref parameter at runtime (1 个回答) 关闭 2 年前。 为了即时创建委托(dele
我正在尝试获取图像的 dct。一开始我遇到了错误 The function/feature is not implemented (Odd-size DCT's are not implemented
我正在尝试使用 AFNetworking 的 AFPropertyListRequestOperation,但是当我尝试下载它时,出现错误 预期的内容类型{( “应用程序/x-plist” )}, 得
我在下面收到错误。我知道这段代码的意思,但我不知道界面应该是什么样子: Element implicitly has an 'any' type because index expression is
我尝试将 SignalType 从 ReactiveCocoa 扩展为自定义 ErrorType,代码如下所示 enum MyError: ErrorType { // .. cases }
我无法在任何其他问题中找到答案。假设我有一个抽象父类(super class) Abstract0,它有两个子类 Concrete1 和 Concrete1。我希望能够在 Abstract0 中定义类
我想知道为什么这个索引没有用在 RANGE 类型中,而是用在 INDEX 中: 索引: CREATE INDEX myindex ON orders(order_date); 查询: EXPLAIN
我正在使用 RxJava,现在我尝试通过提供 lambda 来订阅可观察对象: observableProvider.stringForKey(CURRENT_DELETED_ID) .sub
我已经尝试了几乎所有解决问题的方法,其中包括。为 提供类型使用app.use(express.static('public'))还有更多,但我似乎无法为此找到解决方案。 index.js : imp
以下哪个 CSS 选择器更快? input[type="submit"] { /* styles */ } 或 [type="submit"] { /* styles */ } 只是好
我不知道这个设置有什么问题,我在 IDEA 中获得了所有注释(@Controller、@Repository、@Service),它在行号左侧显示 bean,然后转到该 bean。 这是错误: 14-
我听从了建议 registering java function as a callback in C function并且可以使用“简单”类型(例如整数和字符串)进行回调,例如: jstring j
有一些 java 类,加载到 Oracle 数据库(版本 11g)和 pl/sql 函数包装器: create or replace function getDataFromJava( in_uLis
我已经从 David Walsh 的 css 动画回调中获取代码并将其修改为 TypeScript。但是,我收到一个错误,我不知道为什么: interface IBrowserPrefix { [
我是一名优秀的程序员,十分优秀!