简体   繁体   English

加载模块脚本失败:服务器以“text/plain”的非 JavaScript MIME 类型响应。 对模块强制执行严格的 MIME 类型检查

[英]Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking is enforced for module

I followed this video while installing the django debug toolbar as well as thedocs .我在安装 django 调试工具栏以及文档时关注了这个视频。 However, I just cannot get it to work.但是,我无法让它发挥作用。 The mime type error keeps popping up in the console tab of the dev tools.在开发工具的控制台选项卡中不断弹出 MIME 类型错误。

在此处输入图片说明

settings.py设置.py

from pathlib import Path
import os

BASE_DIR = Path(__file__).resolve().parent.parent

SECRET_KEY = 'this is secret'

DEBUG = True

 if DEBUG:
     import mimetypes
     mimetypes.add_type("application/javascript", ".js", True)


INTERNAL_IPS = [
    '127.0.0.1',
]


ALLOWED_HOSTS = [
    'localhost',
    '127.0.0.1',
]


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'debug_toolbar',
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'demo.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'demo.wsgi.application'


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


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',
    },
]


LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static_in_env')]
VENV_PATH = os.path.dirname(BASE_DIR)
STATIC_ROOT = os.path.join(VENV_PATH, 'static_root')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(VENV_PATH, 'mdeia')


# debug toolbar settings

DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.versions.VersionsPanel',
    'debug_toolbar.panels.timer.TimerPanel',
    'debug_toolbar.panels.settings.SettingsPanel',
    'debug_toolbar.panels.headers.HeadersPanel',
    'debug_toolbar.panels.request.RequestPanel',
    'debug_toolbar.panels.sql.SQLPanel',
    'debug_toolbar.panels.staticfiles.StaticFilesPanel',
    'debug_toolbar.panels.templates.TemplatesPanel',
    'debug_toolbar.panels.cache.CachePanel',
    'debug_toolbar.panels.signals.SignalsPanel',
    'debug_toolbar.panels.logging.LoggingPanel',
    'debug_toolbar.panels.redirects.RedirectsPanel',
    'debug_toolbar.panels.profiling.ProfilingPanel',
]


def show_toolbar(request):
    return True

DEBUB_TOOLBAR_CONFIG = {
    'SHOW_TOOLBAR_CALLBACK': show_toolbar
}


urls.py网址.py

from django.conf import settings
from django.contrib import admin
from django.urls import path, include

from .views import home, java_script




urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home, name='home'),
    path('.*\.js', java_script),
]


if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [path('__debug__/', include(debug_toolbar.urls))]

views.py视图.py

from django.shortcuts import render

def home(request):
    return render(request, "index.html", {})



def java_script(request):
    filename = request.path.strip("/")
    data = open(filename, "rb").read()
    return HttpResponse(data, mimetype="application/x-javascript")

base.html基本文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta Content-Type: text/html; charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>
</head>
<body>
    {% block content %}
        
    {% endblock content %}
</body>
</html>

I have also set the HKEY_CLASSES_ROOT\\.js\\Content Type in the registry editor to text/javascript as shown below.我还将注册表编辑器中的HKEY_CLASSES_ROOT\\.js\\Content Type设置为text/javascript ,如下所示。

在此处输入图片说明

There is an exact same question asked here , there was an ask for further info but none was provided and I do not have the ability to add comments.这里问一个完全相同的问题,有人要求提供更多信息,但没有提供,我无法添加评论。 Hence a brand new question.因此,一个全新的问题。

Edit: The toolbar shows up in microsoft edge, WTF!!!编辑:工具栏显示在 microsoft edge,WTF 中!!!

refer below code resolved this issue.参考下面的代码解决了这个问题。

from django.http import JsonResponse
def java_script(request):
    filename = request.path.strip("/")
    data = open(filename, "rb").read()
    # return HttpResponse(data, mimetype="application/x-javascript")
    return JsonResponse(data, safe=False)
    #enter code here

Not An Actual Answer but still不是一个实际的答案,但仍然

I don't know exactly what random thing changed that got the toolbar to start working out of the blue!我不知道究竟是什么随机变化使工具栏突然开始工作! But the toolbar is now showing up in the original project I actually wanted it to work in. And it's still working in edge as well.但是工具栏现在出现在我真正想要它工作的原始项目中。它仍然在边缘工作。

The above project( see question ) was a clean slate to test out the django debug toolbar itself .上面的项目(见问题)是一个全新的测试 django 调试工具栏本身 I wanted to see how/if it works in an isolated environment.我想看看它如何/是否在隔离环境中工作。

The only changes that I remember making are:我记得所做的唯一更改是:

  • Reconnecting a bluetooth device重新连接蓝牙设备
  • Uncheck show small icons in taskbar取消选中在任务栏中显示小图标
  • Auto hide taskbar when in desktop mode在桌面模式下自动隐藏任务栏

The settings and urls code for the Original project is shown below :原始项目的设置和 urls 代码如下所示

settings.py设置.py


import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = Again, this is secret

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True


INTERNAL_IPS = [
    'localhost',
    '127.0.0.1',
]


ALLOWED_HOSTS = [
    'localhost',
    '127.0.0.1',
]


# Application definition

INSTALLED_APPS = [
    'auctions',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'debug_toolbar',
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'commerce.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'commerce.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

AUTH_USER_MODEL = 'auctions.User'

# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

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.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
MEDIA_URL = '/media/'

MEDIA_R00T = os.path.join(BASE_DIR, 'media')


# Default django debug toolbar settings


def show_toolbar(request):
    return True


DEBUG_TOOLBAR_PANELS = [
    'debug_toolbar.panels.versions.VersionsPanel',
    'debug_toolbar.panels.timer.TimerPanel',
    'debug_toolbar.panels.settings.SettingsPanel',
    'debug_toolbar.panels.headers.HeadersPanel',
    'debug_toolbar.panels.request.RequestPanel',
    'debug_toolbar.panels.sql.SQLPanel',
    'debug_toolbar.panels.staticfiles.StaticFilesPanel',
    'debug_toolbar.panels.templates.TemplatesPanel',
    'debug_toolbar.panels.cache.CachePanel',
    'debug_toolbar.panels.signals.SignalsPanel',
    'debug_toolbar.panels.logging.LoggingPanel',
    'debug_toolbar.panels.redirects.RedirectsPanel',
    'debug_toolbar.panels.profiling.ProfilingPanel',
]


DEBUG_TOOLBAR_CONFIG = {
    'SHOW_TOOLBAR_CALLBACK': show_toolbar
}

Project level urls.py项目级 urls.py


from django.conf import settings
from django.contrib import admin
from django.urls import include, path
from django.conf.urls.static import static
import debug_toolbar

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("auctions.urls")),
    path('__debug__/', include(debug_toolbar.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

App level urls.py应用级 urls.py

from django.urls import path

from . import views


app_name = "auctions"
urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("create_listing", views.create_listing, name="create_listing"),
    path("listing/<str:listing>", views.listing_detail, name="detail_view")
]

Test Project测试项目测试项目

Original Project原创项目原创项目

Update更新

I made a some changes to the original project (wanted to make changes to the models) :我对原始项目进行了一些更改(想对模型进行更改)

  • deleted the sqlite .db file删除了 sqlite .db 文件
  • also deleted the migrations folder还删除了迁移文件夹

Unfortunately these actions affected the django debug toolbar, as in made it go away.不幸的是,这些操作影响了 django 调试工具栏,因为它让它消失了。 To bring back the toolbar I did git reset --hard <ref name> where ref name is the previous commit where the toolbar was present .为了恢复工具栏,我做了git reset --hard <ref name> ,其中 ref name 是工具栏所在的先前提交 However, this did not work.然而,这并没有奏效。

Also the the django debug toolbar disappeared from the test project that I had created, even though I did not make any changes to the code or directory structure for that project.此外,django 调试工具栏从我创建的测试项目中消失了,即使我没有对该项目的代码或目录结构进行任何更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 加载模块脚本失败:服务器以非 JavaScript MIME 类型“”响应。 强制执行严格的 MIME 类型检查 - Failed to load module script: The server responded with a non-JavaScript MIME type of “”. Strict MIME type checking is enforced 加载模块脚本失败:服务器以“text/plain”的非 JavaScript MIME 类型响应。 严格的 MIME 类型检查 i - Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain". Strict MIME type checking i 无法加载模块脚本:服务器以“text/plain”的非 JavaScript MIME 类型响应 - Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain" 服务器以“application/octet-stream”的非 JavaScript MIME 类型响应 每个 HTML 对模块脚本强制执行严格的 MIME 类型检查 - The server responded with a non-JavaScript MIME type of "application/octet-stream" Strict MIME type checking is enforced for module scripts per HTML 加载模块脚本失败:服务器以非 JavaScript、CSS MIME 类型“text/x-scss”响应 - Failed to load module script: The server responded with a non-JavaScript, CSS MIME type of “text/x-scss” Vue.js 3 - “加载模块脚本失败:服务器以非 JavaScript MIME 类型“text/html”响应 - Vue.js 3 - “Failed to load module script: The server responded with a non-JavaScript MIME type of ”text/html" Flask:加载模块脚本失败:服务器以“text/html”的非 JavaScript MIME 类型响应 - Flask: Failed to load module script: The server responded with a non-JavaScript MIME type of “text/html” 加载模块脚本失败:服务器响应非 JavaScript MIME 类型“” - Failed to load module script: The server responded with a non-JavaScript MIME type of "" 从&#39;./image.jpeg&#39;结果导入图像无法加载模块脚本服务器以非JavaScript MIME类型“ image / jpegerror”响应 - Import image from './image.jpeg' results Failed to load module script The server responded with a non-JavaScript MIME type of "image/jpegerror 无法加载模块脚本:需要 JavaScript 模块脚本,但服务器响应 MIME 类型为“text/html” - Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM