HTTP 404错误,Django和Gunicorn中的CSS和JavaScript文件

huangapple go评论151阅读模式
英文:

HTTP 404 error for css and javascript files in Django and Gunicorn

问题

实际错误是

因为其MIME类型('text/html')不是受支持的样式表MIME类型,并且启用了严格的MIME检查,所以拒绝应用来自'http://127.0.0.1:8000/static/css/home.css'的样式。
GET http://127.0.0.1:8000/static/js/home.js net::ERR_ABORTED 404(未找到)

当我开始使用Gunicorn作为应用服务器时,出现了这个错误。有关CSS的第一个错误是一个误导。文件一开始就找不到。
Chrome开发者工具显示

请求URL:http://127.0.0.1:8000/static/css/home.css
请求方法:GET
状态代码:404 未找到
引荐者策略:same-origin
连接:关闭
内容长度:8559
内容类型:text/html
日期:2023年6月7日 19:32:29 GMT
引荐者策略:same-origin
服务器:gunicorn

状态代码。我看到所有CSS和JavaScript文件的状态代码都相同。

以下是我的相关设置

settings.py

INSTALLED_APPS = [
    .
    .
    'django.contrib.staticfiles',
    'bootstrap4',
    .
    .
]

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "kubera/static"),
]

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, "static")

import mimetypes
mimetypes.add_type("text/css", ".css", True) 

manage.py collectstatic命令正确复制了文件

~/workspace/djangoapp/src$ python3 manage.py collectstatic
161个静态文件已复制到'/home/<myhomedir>/workspace/djangoapp/src/static'。

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    {% load static %}
    {% load bootstrap4 %}
    {% bootstrap_css %}
    {% bootstrap_javascript jquery='full' %}
    {% bootstrap_messages %}
    <link href="{% static 'css/home.css' %}"
      type="text/css" rel="stylesheet">

    <title>{% block title %}Parier Config Central {% endblock %}</title>
  </head>
  <body>
    <main>
      <div class="container-fluid headDiv">
        主要div内容在此显示
      </div>
    </main>
    <script type="text/javascript" src="{% static 'js/home.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/main.js' %}"></script>
  </body>
</html>

我可以看到所有的HTML内容都正确。在服务器端控制台上,我看到以下错误调试消息

~/workspace/djangoapp/src$ gunicorn --bind 127.0.0.1:8000 <myappname>.wsgi
[2023-06-07 12:32:24 -0700] [68057] [INFO] 启动gunicorn 20.1.0
[2023-06-07 12:32:24 -0700] [68057] [INFO] 在:http://127.0.0.1:8000 (68057)上听取
[2023-06-07 12:32:24 -0700] [68057] [INFO] 使用worker:sync
[2023-06-07 12:32:24 -0700] [68058] [INFO] 使用pid引导工作:68058
未找到:/static/css/home.css
未找到:/static/js/home.js
未找到:/static/js/main.js
未找到:/static/images/BlankPicture.png
未找到:/static/css/home.css
未找到:/favicon.ico

编辑: Gunicorn套接字和服务配置
/etc/systemd/system/gunicorn.socket

[Unit]
Description=gunicorn套接字

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

/etc/systemd/system/gunicorn.socket

[Unit]
Description=gunicorn守护进程
Requires=gunicorn.socket
After=network.target

[Service]
User=<username>
Group=<usergroup>
WorkingDirectory=/绝对路径到您的wsgi文件目录
ExecStart=/usr/local/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          <projectname>.wsgi:application

[Install]
WantedBy=multi-user.target

配置好gunicorn套接字和服务后,启动它们。

~/workspace/djangoapp/src$ sudo systemctl start gunicorn.socket
~/workspace/djangoapp/src$ sudo systemctl enable gunicorn.socket
~/workspace/djangoapp/src$ sudo systemctl status gunicorn.socket
~/workspace/djangoapp/src$ sudo systemctl daemon-reload
~/workspace/djangoapp/src$ sudo systemctl restart gunicorn

NGINX配置文件
/etc/nginx/sites-available/

server {
    listen 80;
    server_name 127.0.0.1;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /静态目录的父目录的绝对路径;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

启用您的应用程序

sudo ln -s /etc/nginx/sites-available/<app-name> /etc/nginx/sites-enabled/
英文:

The actual error is

Refused to apply style from &#39;http://127.0.0.1:8000/static/css/home.css&#39; because its MIME type (&#39;text/html&#39;) is not a supported stylesheet MIME type, and strict MIME checking is enabled.
GET http://127.0.0.1:8000/static/js/home.js net::ERR_ABORTED 404 (Not Found)

This error started happening when I started using Gunicorn as app server. The first error for css is a misdirection. The file was not found to begin with.
Chrome developer tools shows

Request URL:http://127.0.0.1:8000/static/css/home.css
Request Method:GET
Status Code:404 Not Found
Referrer Policy:same-origin
Connection:close
Content-Length:8559
Content-Type:text/html
Date:Wed, 07 Jun 2023 19:32:29 GMT
Referrer-Policy:same-origin
Server:gunicorn

status code. I see the same status code for all the css and javascript files.

Here are my relevant settings

settings.py

INSTALLED_APPS = [
    .
    .
    &#39;django.contrib.staticfiles&#39;,
    &#39;bootstrap4&#39;,
    .
    .
]

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, &quot;kubera/static&quot;),
]

STATIC_URL = &#39;/static/&#39;

STATIC_ROOT = os.path.join(BASE_DIR, &quot;static&quot;)

import mimetypes
mimetypes.add_type(&quot;text/css&quot;, &quot;.css&quot;, True) 

manage.py collectstatic command copied the files correctly

~/workspace/djangoapp/src$ python3 manage.py collectstatic
161 static files copied to &#39;/home/&lt;myhomedir&gt;/workspace/djangoapp/src/static&#39;.

index.html

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
    {% load static %}
    {% load bootstrap4 %}
    {% bootstrap_css %}
    {% bootstrap_javascript jquery=&#39;full&#39; %}
    {% bootstrap_messages %}
    &lt;link href=&quot;{% static &#39;css/home.css&#39; %}&quot;
      type=&quot;text/css&quot; rel=&quot;stylesheet&quot;&gt;

    &lt;title&gt;{% block title %}Parier Config Central {% endblock %}&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;main&gt;
      &lt;div class=&quot;container-fluid headDiv&quot;&gt;
        Main div content shown here
      &lt;/div&gt;
    &lt;/main&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;{% static &#39;js/home.js&#39; %}&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;{% static &#39;js/main.js&#39; %}&quot;&gt;&lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;

I can see all the html content correctly. On the server side console, I see following error debug messages

~/workspace/djangoapp/src$ gunicorn --bind 127.0.0.1:8000 &lt;myappname&gt;.wsgi
[2023-06-07 12:32:24 -0700] [68057] [INFO] Starting gunicorn 20.1.0
[2023-06-07 12:32:24 -0700] [68057] [INFO] Listening at: http://127.0.0.1:8000 (68057)
[2023-06-07 12:32:24 -0700] [68057] [INFO] Using worker: sync
[2023-06-07 12:32:24 -0700] [68058] [INFO] Booting worker with pid: 68058
Not Found: /static/css/home.css
Not Found: /static/js/home.js
Not Found: /static/js/main.js
Not Found: /static/images/BlankPicture.png
Not Found: /static/css/home.css
Not Found: /favicon.ico

Edit: Gunicorn socket and service configuration
/etc/systemd/system/gunicorn.socket

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

/etc/systemd/system/gunicorn.socket

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=&lt;username&gt;
Group=&lt;usergroup&gt;
WorkingDirectory=/absolute-path-to-your-wsgi-file-directory
ExecStart=/usr/local/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          &lt;projectname&gt;.wsgi:application

[Install]
WantedBy=multi-user.target

Once you have configured the gunicorn socket and service, start them.

~/workspace/djangoapp/src$sudo systemctl start gunicorn.socket
~/workspace/djangoapp/src$sudo systemctl enable gunicorn.socket
~/workspace/djangoapp/src$sudo systemctl status gunicorn.socket
~/workspace/djangoapp/src$sudo systemctl daemon-reload
~/workspace/djangoapp/src$sudo systemctl restart gunicorn

NGINX config file
/etc/nginx/sites-available/<app-name>

server {
    listen 80;
    server_name 127.0.0.1;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /absolute-path-to-the-parent-of-static-directory;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

Enable your app

sudo ln -s /etc/nginx/sites-available/&lt;app-name&gt; /etc/nginx/sites-enabled/

答案1

得分: 0

这个回答是给像我这样的新手。我只使用了 Django 和 Gunicorn。我没有任何 web 服务器。Django 不提供静态文件服务。Gunicorn 是一个应用服务器,也不提供静态文件服务。你必须有像 NGINX 这样的 web 服务器来提供静态文件服务。一旦我启动了 NGINX,一切都开始正常运作。我将在我的原始问题中更新 Gunicorn 和 Nginx 的设置,以便其他人可以快速参考设置。

英文:

This answer is for noobs like me.
I only had Django up with Gunicorn. I didn't have any web-server. Django doesn't serve static files. Gunicorn is an app server and doesn't serve static files either. You must have a web-server like NGINX to serve the static files.
Everything started to work as soon as I brought up NGINX. I am going to update my original question with Gunicorn and Nginx settings in case someone wants a quick settings reference.

huangapple
  • 本文由 发表于 2023年6月8日 04:34:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定